python - 有没有办法在 tkinter 中实时更新标签?
问题描述
在 Tkinter 的帮助下,我尝试一次打印一个单词(间隔 2 秒睡眠)我尝试了以下代码,它没有按我想要的那样工作。我的代码正在打印彼此堆叠的整个字符串。
经过 n*len(words) 睡眠秒后。
我试图一次只打印一个单词(间隔为 2 秒)
from tkinter import *
from time import sleep
root = Tk()
words = 'Hey there, This is python3'.split()
l = Label(root, text='')
for w in range(len(words)):
sleep(2)
l = Label(root,text = words[w])
#l['text'] = words[w] # this is what I tried
l.pack()
root.mainloop()
我尝试了上面评论的声明,认为这可能会更新,但根本没有像我预期的那样工作。
解决方案
看看这个例子:
from tkinter import *
root = Tk()
words = 'Hey there, This is python3'.split()
l = Label(root) #creating empty label without text
l.pack()
w = 0 #index number
def call():
global w
if w <= len(words)-1: #if it is in the range of the list
l.config(text=words[w]) #change the text to the corresponding index element
w += 1 #increase index number
root.after(2000,call) #repeat the function after 2 seconds
else:
print('Done') # if out of index range, then dont repeat
call() #call the function initially
root.mainloop()
我已经评论了代码以便更好地理解。
using 的方法after()
会重复调用函数,这可能会降低其效率。因此,或者您也可以使用,threading
来启动一个不会使 GUI 冻结的新线程,同时sleep()
:
from tkinter import *
from time import sleep
import threading #import the library
root = Tk()
words = 'Hey there, This is python3'.split()
l = Label(root) #empty label
l.pack() #pack()
def call():
for w in words: #loop through the list
l.config(text=w) #update label with each word over each iteration
sleep(2) #sleep for 2 seconds
threading.Thread(target=call).start() #create a separate thread to not freeze the GUI
root.mainloop()
推荐阅读
- elixir - 如何修改 many_to_many 变更集中的 join_defaults 值?
- python - 使用matplotlib和Python绘制多条线的问题
- github - 如何将文件上传到 github 现有存储库中的文件夹?
- php - 如何根据 Laravel Breeze 中“用户”表中的级别字段将用户重定向到不同的仪表板?
- flutter - 如何在具有多个条件/查询的流构建器中获取数据?
- css - 我的导航栏链接中的左边距不会消失
- uwp - UWP HighContrastScheme 检查本地化环境
- react-native - 具有分页和预览第一个和最后一个项目的 FlatList
- postgresql - 如何将 PostgreSQL 连接到 web2py?
- android - 如何使用java知道在某个小时内醒来的可能性