tkinter 函数如何处理它作为参数的列表,一个接一个,一个接一个?
How does the tkinter function process the lists it takes as arguments, one by one, one by one?
我在 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()
由于 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()
我在 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()
由于 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()