我在 tkinter 中有一個簡單的函式來處理它作為引數的串列。它用 after 方法不斷重復。當按鈕被點擊時,不同的串列作為引數提供給函式。發送第一個串列時沒有問題,但是發送第二個串列時,第一個串列和第二個串列一起處理。我的目標是分別處理每個串列。
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()
uj5u.com熱心網友回復:
由于sample_function永遠重新安排自己,如果您list_1已經回圈,那么在您安排另一個回圈時它不會停止。為了解決這個問題,您需要保持當前計劃任務的狀態,并在計劃新任務時取消它。
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()
uj5u.com熱心網友回復:
我建議在程式啟動時啟動更新計劃任務。然后單擊按鈕只是更新顏色串列:
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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/340145.html
