我有一个有两个按钮的界面。它们有相互排斥的动作,当后台for-loop中的某个条件被满足时,它们就会生成。用户应该点击其中一个按钮,然后按钮应该消失。当在后台运行的for-loop中再次满足条件时,它们可能会重新出现。你可以认为这些按钮是在做 "选择其中一个...... "的事情。后台的for-loop需要等待用户的输入。因此,我使用了 wait_variable
方法的按钮上。
为了建立这个模型,我写了这个MWE。
import tkinter as tk
root = tk.Tk()
a, b = 0, 0
var = tk.IntVar()
def Aaction():
global a
a += 1
var.set(var.get()+1)
b1.destroy()
b2.destroy()
def Baction():
global b
b += 1
var.set(var.get()+1)
b1.destroy()
b2.destroy()
# this happens before A and B are displayed
print('some code executing')
b1 = tk.Button(root, text='A', command=Aaction)
b1.pack()
b2 = tk.Button(root, text='B', command=Baction)
b2.pack()
b1.wait_variable(var)
print('b1 finsihed waiting')
b2.wait_variable(var) # what happens to this? `b2` is deleted when `b` is clicked. so...?
print('b2 finsihed waiting') # this is never reached
# this should happen after either A or B was clicked
print('some more code executing')
root.mainloop()
这段代码并不是我想要的 但它是我在代码中试图解决这个问题的一个抽象。我的问题是:你如何正确解决这个问题?
这样的东西可以用吗?
import tkinter as tk
root = tk.Tk()
def Aaction():
b1.destroy()
b2.destroy()
do_later()
def Baction():
b1.destroy()
b2.destroy()
do_later()
# this happens before A and B are displayed
print('some code executing')
b1 = tk.Button(root, text='A', command=Aaction)
b1.pack()
b2 = tk.Button(root, text='B', command=Baction)
b2.pack()
# this should happen after either A or B was clicked
def do_later():
print('some more code executing')
root.mainloop()