本文介绍了Tkinter:使用 after() 使函数定期运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让一个函数定期运行.目的是在 tkinter 框架上打印串行数据.

I was trying to make a function run periodically. The purpose was to print serial data on a tkinter frame.

最初这工作,使用线程.

Initially this worked, using threads.

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()

但是,我在关闭应用程序时遇到错误.您可以在此处阅读有关此内容的更多信息:关闭我的 tkinter 串行应用程序,给我一个例外

However, i was experiencing error when i was closing my application.You can read more about this here:Closing my tkinter serial app, gives me an exception

所以用户 AST 建议,我应该使用 after() 函数.

So user AST suggested, i should use the after() function.

所以我试过这个:

我保持函数 readSerial() 完全相同.我删除了所有涉及线程的行 (t1).

I kept the function readSerial() exactly the same. I removed all the lines that involved threads (t1).

最后:

root.after(100, readSerial)
root.mainloop()

但这并没有按预期工作.

But this doesn't work as expected.

在我的 tkinter 框架中,只打印串行的第一行,然后没有其他任何内容.

In my tkinter frame, only the first line of the serial is printed, then nothing else.

我怎样才能使用 after() 完成这项工作?正确的方法是什么?

How can i make this work with after()? What is the proper way?

推荐答案

你必须在函数内部使用 after() 以便定期调用它,例如:

You have to use after() inside the function so as to call it periodically, like:

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 毫秒之前被调用.

This will keep on repeating the function roughly every 100 milliseconds, there is no guarantee to call the function exactly at 100 millisecond, but it wont be called before 100 millisecond.

这篇关于Tkinter:使用 after() 使函数定期运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:04