[英]Color changing button in tkinter python
我正在尝试在 tkinter 中创建一个变色按钮。 这是我的代码:
import tkinter as tk
window = tk.Tk()
btn = tk.Button(window, text='Button')
btn.pack(padx=50, pady=30)
rainbow_colors = ['red','purple','yellow','orange','blue',
'lightblue','green','violet','gray','cyan']
color_iterator = iter(rainbow_colors)
def ButtonUpdate():
try:
color = next(color_iterator)
btn.config(bg=color)
except StopIteration:
return
window.after(500, ButtonUpdate)
ButtonUpdate()
window.mainloop()
虽然这确实有效,但我希望按钮不断改变它的颜色。 在我的代码中,它遍历列表一次然后停止。
尝试以下解决方案,使用 itertools 的循环在列表中继续循环,注释中给出的解释和步骤
import tkinter as tk
# 1) Import module
from itertools import cycle
window = tk.Tk()
btn = tk.Button(window, text='Button')
btn.pack(padx=50, pady=30)
rainbow_colors = ['red','purple','yellow','orange','blue',
'lightblue','green','violet','gray','cyan']
color_iterator = iter(rainbow_colors)
#2) Create object of cycle
licycle = cycle(rainbow_colors)
def ButtonUpdate():
try:
# 3) Fetch next element from cycle object
color = next(licycle)
btn.config(bg=color)
except StopIteration:
return
window.after(500, ButtonUpdate)
ButtonUpdate()
window.mainloop()
我只是添加另一种方法,您可以轻松地解决这个问题,而无需导入任何外部模块或任何东西,只需使用简单的 python 索引和if
条件:
idx = 0
def ButtonUpdate(idx):
if idx >= len(rainbow_colors): # Check if idx is out of list, then reset to 0
idx = 0
btn.config(bg=rainbow_colors[idx])
idx += 1
window.after(500,ButtonUpdate,idx)
ButtonUpdate(idx)
您还可以删除所有与iter
相关的代码,因为它不再需要。 您也可以只使用global
,但参数对我来说似乎更有效。
尝试这个:
import tkinter as tk
def my_iterator_looper(_list):
while True:
for i in _list:
yield i
window = tk.Tk()
btn = tk.Button(window, text='Button')
btn.pack(padx=50, pady=30)
rainbow_colors = ['red','purple','yellow','orange','blue',
'lightblue','green','violet','gray','cyan']
color_iterator = my_iterator_looper(rainbow_colors)
def ButtonUpdate():
try:
color = next(color_iterator)
btn.config(bg=color)
except StopIteration:
return
window.after(500, ButtonUpdate)
ButtonUpdate()
window.mainloop()
我创建了自己的迭代器,它使用while True
循环和yield
来不断地循环这些值。 有关yield
如何工作的更多信息,请阅读此
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.