python-3.x - Tkinter:使用 after() 使函数定期运行

标签 python-3.x multithreading tkinter serial-port pyserial

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

相关文章:

python |输入缓冲区中字节过多 RPLidarException : Incorrect Descriptor Starting Bytes when running and plotting with RPLIDAR

python - 如何使用 flask 将数据传递到html页面?

使用 ThreadPool 的 C# Execute 方法(带参数)

Python 标签图像不存在,但 os.path 说它存在

python - Seaborn BarPlot 反转 y 轴并将 x 轴保持在图表区域的底部

python - SQLAlchemy 核心 : Connection is closing unexpectedly

java - 为什么这个简单的 Java 同步代码块示例会根据我锁定的对象提供不同的输出?

c - 读取/预读系统调用的线程安全

python - 在 tkinter 菜单中的帧之间切换

python - 如何从 ttk.Treeview 小部件中清除项目?