首页 > 解决方案 > tkinter 函数如何处理它作为参数的列表,一个接一个,一个接一个?

问题描述

我在 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()

标签: pythonlistfunctiontkinterarguments

解决方案


由于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()

推荐阅读