簡體   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