Tkinter:使用 after() 定期生成函数 运行

Tkinter: make function run periodically with after()

我试图定期创建一个函数 运行。目的是在 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()

但是,我在关闭应用程序时遇到了错误。 您可以在此处阅读更多相关信息:

所以用户 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 毫秒之前调用。