简体   繁体   English

Python tkinter 后方法未按预期工作

[英]Python tkinter after method not working as expected

I'm trying to learn Tkinter module, but I can't undestand why the after method doesn't behave as expected.我正在尝试学习 Tkinter 模块,但我无法理解为什么 after 方法没有按预期运行。 From what I know, it should wait ms milliseconds and then execute the function, but in my case the function gets executed many more time, not considering the time I write.据我所知,它应该等待 ms 毫秒,然后执行 function,但在我的情况下,function 执行的时间要长得多,而不是考虑我写的时间。 Here's the code:这是代码:

from tkinter import *

def doSomething():
    x = int(l["text"])
    l["text"] = str(x + 1)

root = Tk()
root.geometry("300x300")
l = Label(root, text="0")
l.pack()

while True:
    l.after(1000, doSomething)
    root.update()
    if int(l["text"]) >= 5:
        break

root.mainloop() 

After the first 2 seconds the label starts displaying humongous numbers前 2 秒后,label 开始显示大量数字

After the first 2 seconds the label starts displaying humongous numbers前 2 秒后,label 开始显示大量数字

Keep in mind, while True , is an infinite loop, you are making infinite calls to root.after() means alot of events are being scheduled to be called after 1 second.请记住, while True是一个无限循环,但您正在无限调用root.after()意味着许多事件被安排在 1 秒后被调用。 Better way to do this is to remove your while and move it all inside your function.更好的方法是删除你的while并将其全部移动到 function 中。

from tkinter import *

root = Tk()

def doSomething():
    x = int(l["text"])
    l["text"] = x + 1
    if int(l["text"]) < 5: # Only repeat this function as long as this condition is met
        l.after(1000, doSomething)

root.geometry("300x300")
l = Label(root, text="0")
l.pack()

doSomething()

root.mainloop() 

Though the best way to write the function would be to create a variable and increase the value of that variable inside the function and then show it out:虽然编写 function 的最佳方法是创建一个变量并在 function 中增加该变量的值,然后将其显示出来:

from tkinter import *

root = Tk()

count = 0 # Initial value
def doSomething():
    global count # Also can avoid global by using parameters
    count += 1 # Increase it by 1 
    l['text'] = count # Change text
    if count < 5:
        l.after(1000, doSomething)

root.geometry("300x300")
l = Label(root, text=count)
l.pack()

doSomething() # If you want a delay to call the function initially, then root.after(1000,doSomething)

root.mainloop() 

This way you can reduce the complexity of your code too and make use of the variable effectively and avoid nasty type castings;)这样您也可以降低代码的复杂性并有效地利用变量并避免讨厌的类型转换;)

You are using infinite loop when using while True.使用 while True 时正在使用无限循环。 Correct way is:正确的做法是:

from tkinter import *

def doSomething():
    x = int(l["text"])
    l["text"] = str(x + 1)
    if x < 5:
        l.after(1000, doSomething)

root = Tk()
root.geometry("300x300")
l = Label(root, text="0")
l.pack()


doSomething()


root.mainloop() 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM