立即执行方法后的 Tkinter [英] Tkinter after method executing immediately
问题描述
TKinter 'after' 方法立即执行,然后在执行后暂停 3 秒.如果我还在 CheckStatus 函数中使用了 'after' 方法,它会进入一个快速循环并且永远不会到达 mainloop().
The TKinter 'after' method is executing immediately, then pausing for the 3 second time after execution. If I also use the 'after' method in my CheckStatus function, it goes onto a rapid loop and never gets to the mainloop().
我做错了什么?文档说这个函数会在暂停时间之后被调用,但它实际上发生在之前.我想每秒调用一次 CheckStatus 以获取 Raspberry Pi 上的硬件输入,并让正常的主循环响应用户事件.
What am I doing wrong? the documentation says the function would be called after the pause time, but its actually happening before. I want to call CheckStatus every second for a hardware input on Raspberry Pi, as well as have the normal mainloop responding to user events.
from tkinter import *
def DoClick(entries):
global ButCount
ButCount += 1
print("ButCount", ButCount, "TimeCount", TimeCount)
def newform(root):
L1 = Label(root, text = "test of 'after' method which seems to call before time")
L1.pack()
def CheckStatus():
global TimeCount
TimeCount += 1
print("In CheckStatus. ButCount", ButCount, "TimeCount", TimeCount)
# root.after(3000, DoTime())
root = Tk()
ButCount = 0
TimeCount = 0
if __name__ == '__main__':
FormData = newform(root)
root.bind('<Return>', (lambda event, e=FormData: fetch(e)))
b1 = Button(root, text='Click me', command=(lambda e=FormData: DoClick(e)))
b1.pack()
print("Before root.after(")
root.after(3000, CheckStatus())
print("Done root.after(")
root.mainloop()
推荐答案
您使用后不正确.考虑这行代码:
You are using after incorrectly. Consider this line of code:
root.after(3000, CheckStatus())
和这个完全一样:
result = CheckStatus()
root.after(3000, result)
看到问题了吗?after 需要一个可调用的——对函数的引用.
See the problem? after requires a callable -- a reference to the function.
解决方案是向函数传递一个引用:
The solution is to pass a reference to the function:
root.after(3000, CheckStatus)
即使您没有问,对于可能想知道如何传递参数的人:您也可以包含位置参数:
And even though you didn't ask, for people who might be wondering how to pass arguments: you can include positional arguments as well:
def example(a,b):
...
root.after(3000, example, "this is a", "this is b")
这篇关于立即执行方法后的 Tkinter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!