如何在python中使用Tkinter循环遍历标签中的列表?

如何在python中使用Tkinter循环遍历标签中的列表?,python,loops,user-interface,tkinter,label,Python,Loops,User Interface,Tkinter,Label,我正在尝试创建一个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_l

我正在尝试创建一个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()
这是到目前为止我的代码。当我运行它时,结果只是一个白色屏幕。同样,我希望标签在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循环,则需要时间。睡眠,但即使使用window.update,也会冻结GUI。更新窗口更新,但GUI窗口将无响应

func方法主要有两个参数:

ms-运行函数的时间(毫秒) func-在给定ms完成后运行的函数。
我应该补充一点,我对Tkinter完全陌生,所以请原谅我犯的任何愚蠢的错误。使用time.sleep会使GUI无响应。有没有办法在两者之间暂停?window.after是一种方法。但是我们无法运行此代码,因此我们不知道什么是公共推文或推文。你想知道为什么会显示一个巨大的白色屏幕吗?这是您的标签背景和配置的大小。只需减小大小并从主块调用函数