Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

python - Tkinter after method executing immediately

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

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are using after incorrectly. Consider this line of code:

root.after(3000, CheckStatus())

It is exactly the same as this:

result = CheckStatus()
root.after(3000, result)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...