我试图让一个函数定期运行。目的是在 tkinter 框架上打印串行数据。
最初,使用线程,这是有效的。
def readSerial():
global val1
ser_bytes = ser.readline()
ser_bytes = ser_bytes.decode("utf-8")
val1 = ser_bytes
scrollbar.insert("end", val1)
scrollbar.see("end") #autoscroll to the end of the scrollbar
t1 = continuous_threading.PeriodicThread(0.1, readSerial)
frame2 = tk.Frame(root, bg='#80c1ff') #remove color later
frame2.place(relx=0, rely=0.1, relheight=1, relwidth=1, anchor='nw')
scrollbar = scrolledtext.ScrolledText(frame2)
scrollbar.place(relx=0, rely=0, relheight=0.9, relwidth=1, anchor='nw')
t1.start()
root.mainloop()
但是,当我关闭应用程序时遇到错误。 您可以在这里阅读更多相关内容: Closing my tkinter serial app, gives me an exception
所以用户 AST 建议,我应该使用 after()
函数。
所以我尝试了这个:
我使函数readSerial()
保持完全相同。我删除了所有涉及线程的行 (t1
)。
最后是这个:
root.after(100, readSerial)
root.mainloop()
但这并没有按预期工作。
在我的 tkinter 框架中,仅打印序列的第一行,然后没有其他内容。
如何使用 after()
实现此功能?正确的做法是什么?
最佳答案
您必须在函数内部使用 after()
以便定期调用它,例如:
def readSerial():
global val1
ser_bytes = ser.readline()
ser_bytes = ser_bytes.decode("utf-8")
val1 = ser_bytes
scrollbar.insert("end", val1)
scrollbar.see("end") #autoscroll to the end of the scrollbar
root.after(100,readSerial) # 100 ms is 0.1 second, you can change that
.... # Same code but remove the t1
readSerial()
root.mainloop()
这将继续大约每 100 毫秒重复一次该函数,不能保证恰好在 100 毫秒调用该函数,但不会在 100 毫秒之前调用该函数。
关于python-3.x - Tkinter:使用 after() 使函数定期运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66413081/