0

The code below takes each item from a list in turn, prints its name and changes the colour attribute of a frame. That all works but it happens instantaneously instead of at 1000ms intervals. Is it not done to use a while loop with 'after'?

import tkinter as tk

list= ['red','green','orange','thistle','yellow']

items= (i for i in list)

def alt_colour():
    while True:                     
        try:

            item=next(items)
            print(f'item is {item}')        
            frame['bg']=item
            frame.after(1000,alt_colour)
        except StopIteration:
            #list exhausted
            break   


root=tk.Tk()
frame=tk.Frame(root,width=200,height=100,bg='blue')
frame.pack()

btn=tk.Button(root,command=alt_colour,text='Change Colour')
btn.pack()
root.mainloop()
ragim_w
  • 1
  • 2

1 Answers1

0

Just remove the while loop:

import tkinter as tk

list= ['red','green','orange','thistle','yellow']

items= (i for i in list)

def alt_colour():                 
    try:
        item=next(items)
        print(f'item is {item}')        
        frame['bg']=item
        frame.after(1000,alt_colour)
    except StopIteration:
        #list exhausted
        pass


root=tk.Tk()
frame=tk.Frame(root,width=200,height=100,bg='blue')
frame.pack()

btn=tk.Button(root,command=alt_colour,text='Change Colour')
btn.pack()
root.mainloop()
Prudhvi
  • 1,095
  • 1
  • 7
  • 18