[英]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.