首页 > 解决方案 > Python tkinter after method causes window to freeze

问题描述

I've looked around stackoverflow and am pretty sure this isn't a duplicate. I need to poll a queue every 1ms (or as quickly as possible), and this has to run in the same thread as my tkinter window otherwise I can't update my labels from the queue data. (someone correct me if i'm wrong here). Currently my code looks like this:

def newData():
    global gotNewData
    if q.get == 1: #if there is new data
        updateVariables() #call the function to update my labels with said data
        q.queue.clear() #clear the queue
        gotNewData = 0 #no new data to get
        q.put(gotNewData)
        MainPage.after(1, newData)
    else:
        MainPage.after(1, newData)

however when I run this code, my tkinter window freezes instantly. I commented out the line which calls the other function and it still freezes so i'm pretty sure it's this function which is causing the problem. Any help is greatly appreciated.

标签: pythontkinter

解决方案


因此,如果您必须使用线程,我会做的是StringVar()在线程函数中使用 a 而不必直接使用小部件。

我觉得每秒1000次是多余的。也许每秒做 10 次。

看看这个例子,如果你有任何问题,请告诉我。

import tkinter as tk
import threading
root = tk.Tk()

lbl = tk.Label(root, text="UPDATE ME")
lbl.pack()

q_value = tk.StringVar()

q = tk.Entry(root, textvariable=q_value)
q.pack()


def updateVariables(q):
    lbl.config(text=q)


def newData(q):
    if q.get() != '':
        updateVariables(q.get())
        root.after(100, lambda: newData(q))

    else:
        root.after(100, lambda: newData(q))
        print("not anything")


thread = threading.Thread(target=newData, args=(q_value, ))
thread.start()

root.mainloop()

推荐阅读