我有一个 tkinter 界面,其中有两个按钮用于触发应用程序的两种模式,还有一个标签显示其所处的模式。单击按钮时,调用的结果函数需要一段时间才能执行并返回。这导致我的鼠标光标旋转并且按钮基本上被“卡住”,直到该函数完成执行后我才能单击另一个按钮。
我想要的行为是单击一个按钮,它异步运行该函数(新线程)并使按钮再次可单击。如果单击另一个按钮,第一个线程会立即被终止,新的函数/线程会异步启动。
我该如何实现这一目标?
def alert_mode(var):
print("Entering Alert Mode")
var.set("Current mode: Alert")
// do stuff that takes a while to return
def capture_mode(var):
print("Entering Capture Mode")
var.set("Current mode: Capture")
// do stuff that takes a while to return
root = tk.Tk()
root.geometry('400x400')
var = StringVar()
var.set("Current mode: Alert")
text = tk.Label(root, text="Current mode: Alert", textvariable=var, fg="blue", font=("Arial", 18))
text.pack(pady=8)
b = tk.Button(root, text="Alert mode", height=10, width=15, font=("Arial",14), command=lambda: alert_mode(var))
b.pack()
b2 = tk.Button(root, text="Capture mode", height=10, width=15, font=("Arial",14), command=lambda: capture_mode(var))
b2.pack()
root.mainloop()
编辑:
好的,这是更新后的代码。我试图弄清楚如何启动和停止线程,但这并不完全按照我想要的方式工作。我实际上不希望两个线程同时运行。它要么是警报模式,要么是捕获模式。重点是,我不希望 GUI 在任一模式运行时卡住,以便用户可以随时切换到其他模式。
def alert_mode(var):
print("Entering Alert Mode")
var.set("Current mode: Alert")
// do stuff that takes a while to return
def capture_mode(var):
print("Entering Capture Mode")
var.set("Current mode: Capture")
// do stuff that takes a while to return
def start_alert_thread(var):
t = threading.Thread(target=alert_mode, args=(var,))
t.start()
t.join()
def start_capture_thread(var):
t2 = threading.Thread(target=alert_mode, args=(var,))
t2.start()
t2.join()
root = tk.Tk()
var = StringVar()
var.set("Current mode: Alert")
text = tk.Label(root, text="Current mode: Alert", textvariable=var, fg="blue", font=("Arial", 18))
text.pack(pady=8)
b = tk.Button(root, text="Alert mode", height=10, width=15, font=("Arial",14), command=lambda: start_alert_thread(var))
b.pack()
b2 = tk.Button(root, text="Capture mode", height=10, width=15, font=("Arial",14), command=lambda: start_capture_thread(var))
b2.pack()
root.mainloop()
最佳答案
使用线程,
import threading
option = 0
def buttonOne():
global option
if option == 2:
"kill statement (not sure what)"
option = 1
else:
option = 1
def buttonTwo():
global option
if option == 1:
"kill statement (not sure what)"
option = 2
else:
option = 2
让按钮运行这样的函数。
def threadButtonOne():
threading.Thread(target=buttonOne).start()
关于python - tkinter 按钮单击启动线程以防止 GUI 卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40756417/