【问题标题】:How does the tkinter function process the lists it takes as arguments, one by one, one by one?tkinter 函数如何处理它作为参数的列表,一个接一个,一个接一个?
【发布时间】:2021-12-13 12:35:40
【问题描述】:

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

【问题讨论】:

    标签: python list function tkinter arguments


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2022-11-20
      • 1970-01-01
      • 2012-12-01
      • 2020-07-24
      • 2023-03-22
      • 1970-01-01
      • 2021-03-19
      • 2019-02-19
      • 2016-06-21
      相关资源
      最近更新 更多