如何使用 Tkinter 遍历标签中的列表?

How to loop through a list in a label using Tkinter?

我正在尝试创建一个 GUI,它只是在一段时间内一个接一个地打印消息。

list_of_tweets = [1, 2, 3, 4, 5]


for i in list_of_tweets:
    print(i)
    time.sleep(10)

window = Tk()
window.geometry("800x400")

window.title("Twitterscreen")

variable=StringVar()

def update_label():
    while True:
        for i in list_of_tweets:
            print(i)
            time.sleep(10)
        variable.set(str(i))
        window.update()

label = Label(master=window,
              background='white',
              foreground='black',
              font=('Helvetica', 20),
              width=14,
              height=3)
label.config(width=200, height=300)
label.pack()

mainloop()

到目前为止,这是我的代码。当我 运行 它时,结果只是一个白屏。同样,我希望标签一次打印一个 list_of_tweets,中间间隔 10 秒。

试试这个标签:

display_text = StringVar()
label=Label(window, textvariable=display_text)


text='Your message'
display_text.set(text)

首先将您的标签制作成:

label = Label(master=window,
              background='white',
              foreground='black',
              font=('Helvetica', 20),
              width=200,
              height=300)

现在我在这里使用的想法是索引列表直到到达列表中的最后一项,而不是使用 for 循环。所以把你的函数改成:

count = 0 #index number 
def update_label():
    global count
    label.config(text=list_of_tweets[count]) #show the current indexed item
    count += 1 #increase the index number 
    rep = window.after(1000,update_label) #repeat this process every 1 second
    
    if count >= len(list_of_tweets): #if the index number greater than or equal to length of list
        window.after_cancel(rep) #stop repeating 

所以最终代码将是:

from tkinter import *

list_of_tweets = [1, 2, 3, 4, 5]

window = Tk()
window.geometry("800x400")

window.title("Twitterscreen")

variable = StringVar() #no use here, dont know why you would use it here

count = 0 
def update_label():
    global count

    label.config(text=list_of_tweets[count])
    count += 1
    rep = window.after(1000,update_label)
    
    if count >= len(list_of_tweets):
        window.after_cancel(rep)
    
label = Label(master=window,
              background='white',
              foreground='black',
              font=('Helvetica', 20),
              width=200,
              height=300) # no need to configure it separately when you can declare it directly

label.pack()
update_label() # call the function initially

mainloop()

为什么它在您的示例中不起作用?首先,您将 StringVar() 的值设置到文本中是正确的,但是 StringVar() 根本与标签无关。使用 for 循环,你需要 time.sleep() 但这会冻结 GUI,即使你使用 window.update() window 更新,但 GUI window将没有反应。

after(ms,func)方法主要有两个参数:

  • ms - 成为 运行 函数的时间(以毫秒为单位)
  • func - 在给定 ms 完成后 运行 的函数。