python - 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.
解决方案
因此,如果您必须使用线程,我会做的是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()
推荐阅读
- javascript - 使用拖放更改列表项的顺序
- excel - 无法在 Automation Anywhere 10 中将 Excel 用作数据库
- c# - How to extract the summary value text $39 from the html provided through Selenium
- javascript - browser.tabs 在 web 扩展的弹出 angular 应用程序中未定义
- r - 无法在 addCircleMarkers 中设置颜色参数
- git - PhpStorm 和预提交钩子与 PHP-CS-Fixer 修改 php 文件中的空白行数
- wpf - WPF 从样式触发器中覆盖样式
- ionic-framework - 我无法在 ios 中安装 sudo ionic cordova plugin add phonegap-plugin-push --variable SENDER_ID=XXXXXXXX
- javascript - 有没有办法从 $uibModal 中删除 windowClass?
- javascript - 在 Firestore Firebase 中插入和合并特定字段