Advik
Advik

Reputation: 43

How to get random text to appear every few seconds from a list?

I can get random text to appear and disappear but I'm not able to figure out how to get a random string to reappear by itself.

import tkinter as tk
import random

root = tk.Tk()


foo = ['1', '2', '3','a', 'b', 'c']

label = tk.Label(root, text=random.choice(foo))
label.pack()
root.after(2000, label.destroy)

root.mainloop()

Upvotes: 0

Views: 144

Answers (2)

quamrana
quamrana

Reputation: 39354

Did you mean to have a function update the text in the Label?

import tkinter as tk
import random

root = tk.Tk()

foo = ['1', '2', '3','a', 'b', 'c']

label = tk.Label(root)
label.pack()

def after():
    label.config(text=random.choice(foo))
    root.after(2000, after)
    
after()

root.mainloop()

Upvotes: 2

jizhihaoSAMA
jizhihaoSAMA

Reputation: 12672

You could use a function to change the text in label directly, like:

import tkinter as tk
import random

def change_the_label():
    label["text"] = random.choice(foo)
    root.after(2000, change_the_label)

root = tk.Tk()
foo = ['1', '2', '3','a', 'b', 'c']

label = tk.Label(root,text=random.choice(foo))
label.pack()
root.after(2000, change_the_label)

root.mainloop()

Upvotes: 1

Related Questions