Python Tkinter方法后立即执行

Python Tkinter方法后立即执行,python,tkinter,Python,Tkinter,TKinter“after”方法立即执行,然后在执行后暂停3秒钟。如果我在CheckStatus函数中也使用'after'方法,它将进入一个快速循环,并且永远不会到达mainloop() 我做错了什么?文档中说该函数将在暂停时间之后调用,但实际上它发生在暂停时间之前。我希望每秒调用CheckStatus以获取Raspberry Pi上的硬件输入,并让正常的主循环响应用户事件 from tkinter import * def DoClick(entries): global ButCo

TKinter“after”方法立即执行,然后在执行后暂停3秒钟。如果我在CheckStatus函数中也使用'after'方法,它将进入一个快速循环,并且永远不会到达mainloop()

我做错了什么?文档中说该函数将在暂停时间之后调用,但实际上它发生在暂停时间之前。我希望每秒调用CheckStatus以获取Raspberry Pi上的硬件输入,并让正常的主循环响应用户事件

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()
从tkinter导入*
def DoClick(条目):
全局ButCount
但计数+=1
打印(“ButCount”,ButCount,“TimeCount”,TimeCount)
def新表单(根):
L1=标签(root,text=“测试似乎在时间之前调用的'after'方法”)
L1.pack()
def CheckStatus():
全局时间计数
时间计数+=1
打印(“处于CheckStatus.ButCount”,ButCount,TimeCount,TimeCount)
#root.after(3000,DoTime())
root=Tk()
但计数=0
时间计数=0
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
FormData=newform(根)
bind(“”,(lambda事件,e=FormData:fetch(e)))
b1=按钮(root,text='Click me',command=(lambda e=FormData:DoClick(e)))
b1.pack()
打印(“根目录前。根目录后(”)
root.after(3000,CheckStatus())
打印(“完成根目录后(”)
root.mainloop()

<代码> 您使用错误。请考虑此代码行:

root.after(3000, CheckStatus())
与此完全相同:

result = CheckStatus()
root.after(3000, result)
看到问题了吗?after需要一个可调用的函数引用

解决方案是向函数传递一个引用:

root.after(3000, CheckStatus)
即使您没有询问,对于可能想知道如何传递参数的人:您也可以包括位置参数:

def example(a,b):
    ...
root.after(3000, example, "this is a", "this is b")

您的代码中有一个bug,包括:

root.after(3000, CheckStatus())
这需要:

root.after(3000, CheckStatus)
#                           ^^ parens removed.
传入
CheckStatus()
实际上调用func,而不是传入其引用

听起来您还想反复调用CheckStatus。您可以通过在CheckStatus中进行递归调用来实现这一点。您已经得到:

# root.after(3000, DoTime())
在您的代码中,在
CheckStatus()
中。您可能希望将其更改为:

root.after(3000, CheckStatus)
以获得异步检查


另外,根据您实际尝试执行的操作,您可能希望“递归”调用是有条件的。

after()
类似于
comman=
bind()
需要
回调
-它意味着在您的代码
根目录中没有
()
。after(3000,CheckStatus)
没有
()
BTW:非常感谢!有趣的是,不正确的用法改变了计时。