英文:
How can I change a label text after a specific time without after() function in tkinter python?
问题
我尝试实现我的结果的代码:
from tkinter import*
import time
root=Tk()
lyrics=StringVar()
lyrics.set("释放")
l=Label(root,textvariable=lyrics)
l.pack()
def change_text():
lyrics.set("你!!")
print('ses')
time.sleep(6.9)
change_text()
mainloop()
这个问题的主要问题是窗口在10秒后才显示出来。如果我将mainloop()
移到time.sleep()
函数之前,那么time.sleep()
函数会在应用程序关闭后执行。原因很简单,我没有使用after()
函数,因为after()
函数不接受小数秒值。任何帮助都将不胜感激。
英文:
The code i tried to accomplish my result:
> from tkinter import*
> import time
> root=Tk()
> lyrics=StringVar()
> lyrics.set("unleash")
> l=Label(root,textvariable=lyrics)
> l.pack()
> def change_text():
> lyrics.set("you!!")
> print('ses')
>
>
> time.sleep(6.9)
> change_text()
> mainloop()
The problems in this are like the window is displayed after 10 sec. If I shift the mainloop()
before the time.sleep()
function the time.sleep()
executes after the app is closed. The reason is simple that I didn't use after() function because the after()
function doesn't accepts the sec value in decimal.
Any help is appreciated
答案1
得分: 2
after()
函数接受以毫秒为单位的延迟参数,你应该传递 6900
而不是 6.9
。参见:https://www.tcl.tk/man/tcl8.4/TclCmd/after.html
问题在于 mainloop()
阻止了进一步的执行。你可以始终使用后台线程:
def bg_thread():
time.sleep(6.9)
change_text()
thread = threading.Thread(target=bg_thread)
thread.start()
mainloop()
当然,线程引入了一系列挑战。在使用线程时,确保你知道自己在做什么是个好主意。
另请参阅:
https://docs.python.org/3/library/threading.html#threading.Thread
https://stackoverflow.com/questions/29158220/tkinter-understanding-mainloop
https://stackoverflow.com/questions/8683217/when-do-i-need-to-call-mainloop-in-a-tkinter-application
英文:
The after()
function takes the delay argument in milliseconds, where you would pass 6900
instead of 6.9
. See: https://www.tcl.tk/man/tcl8.4/TclCmd/after.html
The problem is that mainloop()
blocks further execution. You can always use a background thread:
def bg_thread():
time.sleep(6.9)
change_text()
thread = threading.Thread(target=bg_thread)
thread.start()
mainloop()
Threading, of course, brings with it a whole host of challenges. It's a good idea to make sure you know what you're doing when working with threads.
See also:
https://docs.python.org/3/library/threading.html#threading.Thread
https://stackoverflow.com/questions/29158220/tkinter-understanding-mainloop
https://stackoverflow.com/questions/8683217/when-do-i-need-to-call-mainloop-in-a-tkinter-application
答案2
得分: -1
import time
def update_label():
///在这里更新标签文本
label.config(text="新标签文本")
///在更新标签之前等待5秒
time.sleep(5)
update_label()
英文:
import time
def update_label():
///update label text here
label.config(text="New label text")
/// wait for 5 seconds before updating the label
time.sleep(5)
update_label()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论