Tkinter和多线程 [英] Tkinter and multi-threading
问题描述
我正在使用以下代码检查Tkinter是否与多线程一起工作.但是以下代码不起作用(Gui在运行后立即无响应).谁能解释为什么它不起作用?
I was using the following code to examine if Tkinter works along with multithreading. But the following code doesn't work (the Gui becomes unresponsive as soon as it runs). Can anyone please explain why it doesn't work?
from threading import Thread
import tkinter as tk
window = tk.Tk()
label = tk.Label(window, text='Hello')
label.pack()
def func():
i = 1
while True:
label['text'] = str(i)
i += 1
Thread(target=func).start()
Thread(target=window.mainloop).start()
推荐答案
它不起作用,因为Tkinter不支持多线程.与Tkinter小部件交互的所有内容都需要在主线程中运行.如果要使用多线程,请将GUI放在主线程中,而其他代码放在工作线程中,并在它们之间使用线程安全队列进行通信.
It doesn't work because Tkinter doesn't support multithreading. Everything that interacts with a Tkinter widget needs to run in the main thread. If you want to use multithreading, put the GUI in the main thread and your other code in a worker thread, and communicate between them with a thread safe queue.
这篇关于Tkinter和多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!