繁体   English   中英

有没有办法在 tkinter 中实时更新标签?

[英]Is there a way to update label in real-time in 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() 

我已经注释了代码以更好地理解。

使用after()的方法会反复调用该函数,可能会降低其效率。 因此,您也可以使用threading来启动一个新线程,该线程不会在sleep()时使 GUI 冻结:

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

使用线程的简单答案,因为 time.sleep(2) 将使整个 tkinter 在实际显示窗口之前等待几秒钟。

from tkinter import *
import time
from threading import Thread
root = Tk()

words = 'Hey there, This is python3'.split()
l = Label(root, text='')
l.pack()

def show_words():
    for word in words:
        time.sleep(2)
        l.configure(text=word)

thread = Thread(target = show_words)
thread.start()

root.mainloop()

好吧,您首先需要将 mainloop() 从 for loof 中取出,因为它只是发送命令再次运行根,因此只打印第一个单词。 我也使用了一个计时器和一个新屏幕(注意:你也可以在 root 上做同样的事情),我启动了计时器并发送一个命令在当前时间的特定时间后运行 def。我希望帮助了你。

from tkinter import *
import threading
from time import sleep
root = Tk()
words = 'Hey there, This is python3'.split()
l = Label(root, text='')
print(words);
def newWindow():
         global newScreen
         newScreen=Toplevel()
         newScreen.title("Rahul Screen")
         newScreen.geometry("300x300+15+15")
         newScreen.resizable(0,0)
         l=Label(newScreen,text='')
         for w in range(len(words)):
             print(w);
             sleep(2)
             l = Label(newScreen,text = words[w])
             l.pack()
start_time = threading.Timer(2,newWindow)
start_time.start()
root.mainloop()

暂无
暂无

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

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