我正在尝试更新标签,以显示它通过队列接收到的数字时正在递减的数字。我可以看到它正在控制台中打印,但是标签没有改变。任何帮助或建议都会有所帮助!
这是我的代码:
import tkinter as tk
import time
import threading
import queue
class GUIApp:
def __init__(self):
self.root = tk.Tk()
self.buttonCountDown = tk.Button(text='Count Down', command=self.countDownAction)
self.buttonCountDown.pack()
self.label = tk.Label(text='default')
self.label.pack()
self.queue = queue.Queue()
self.root.mainloop()
def countDown(self, seconds):
for i in range(seconds, 0, -1):
self.queue.put(i)
time.sleep(1)
def listenToQueue(self):
while True:
try:
if self.queue.empty() == False:
print(self.queue.get(0))
self.label['text'] = self.queue.get(0)
elif self.queue.empty() == True:
pass
except queue.Empty:
pass
def countDownAction(self):
listenThread = threading.Thread(target=self.listenToQueue)
listenThread.start()
thread = threading.Thread(target=self.countDown, args=(5,))
thread.start()
thread.join()
app = GUIApp()
答案 0 :(得分:1)
您需要了解的第一件事是Queue.get()
删除项目并将其返回,类似于dict.pop()
。因此,当您执行print(self.queue.get(0))
时,该项目已从队列中删除。如果要打印和配置它,必须先将其分配给变量:
def listenToQueue(self):
while True:
try:
if self.queue.empty() == False:
s = self.queue.get(0)
print (s)
self.label['text'] = s
elif self.queue.empty() == True:
pass
except queue.Empty:
pass
接下来,调用thread.join()
将等待线程终止。您无需在当前设置中完全调用此方法。
def countDownAction(self):
listenThread = threading.Thread(target=self.listenToQueue)
listenThread.start()
thread = threading.Thread(target=self.countDown, args=(5,))
thread.start()
#thread.join() #not required