python - 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()
解决方案
由于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()
推荐阅读
- vb.net - 将行添加到数据源后,当垂直滚动条出现在数据绑定数据网格视图中时程序挂起
- flutter - Flutter App中如何设置和使用全局变量
- sql - 如果记录存在,如何显示查询结果,否则在postgresql中不存在记录?
- powershell - 使用 Import-PfxCertificate 导入 pfx 证书
- android-studio - Android Studio 图像未加载
- python - 扁平化多索引数据框
- powershell - 用于计算 AD 帐户到文件夹的 Powershell 过滤器
- c# - 使用 Autofac 多租户库时无法解析服务
- python - 如何在 setup.cfg 中使用带有需求文件的环境标记?
- continuous-integration - 仅在触发另一个手动作业时才运行 CI 作业