首页 > 解决方案 > 有没有办法在 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()

我尝试了上面评论的声明,认为这可能会更新,但根本没有像我预期的那样工作。

标签: pythonpython-3.xtkinter

解决方案


看看这个例子:

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

推荐阅读