I have a simple function in tkinter that processes the list it takes as an argument. It repeats continuously with the after method. When the buttons are clicked, different lists are given to the function as arguments. When the first list is sent, there is no problem, but when the second list is sent, both the first list and the second list are processed together. My goal is to process each list separately.
from tkinter import*
import random
w=Tk()
list_1=["blue","cyan","white"]
list_2=["red","purple","black"]
def sample_function(list):
w.configure(bg=random.choice(list))
w.after(500,lambda:sample_function(list))
Button(text="List 1",command=lambda:sample_function(list_1)).pack()
Button(text="List 2",command=lambda:sample_function(list_2)).pack()
w.mainloop()
CodePudding user response:
Since sample_function
reschedules itself eternally, if you have list_1
already cylcing, it won't stop when you schedule another cycle. To address this, you need to keep a state of the current scheduled task and to cancel it when you schelude a new one.
class AnimationScheduler:
def __init__(self, widget):
self.widget = widget
self._pending = None
def _schedule(self, colors):
self.widget.configure(bg=random.choice(colors))
# Storing the scheduled task for future cancellation
self._pending = self.widget.after(500, lambda: self._schedule(colors))
def animate(self, colors):
if self._pending:
self.widget.after_cancel(self._pending)
self._schedule(colors)
A = AnimationScheduler(w)
Button(text="List 1",command=lambda: A.animate(list_1)).pack()
Button(text="List 2",command=lambda: A.animate(list_2)).pack()
CodePudding user response:
I would suggest to start the update schedule task on program start-up. Then clicking the buttons just update the color list:
from tkinter import*
import random
w = Tk()
list_1 = ["blue","cyan","white"]
list_2 = ["red","purple","black"]
def sample_function(color_set):
if color_set:
print(color_set)
w.configure(bg=random.choice(list(color_set)))
w.after(500, sample_function, color_set)
Button(text="List 1", command=lambda:color_set.update(list_1)).pack()
Button(text="List 2", command=lambda:color_set.update(list_2)).pack()
color_set = set() # store the colors
sample_function(color_set) # start the update loop
w.mainloop()