循环改变 BTN 颜色 BG [Python]
Change BTN color BG with cycle [Python]
我是新手,每次单击 BTN 时,我都试图找到下一种颜色。
我用函数“random.choice”完成了它并且工作得很好但现在我想获得下一种颜色而不是随机颜色。
import tkinter as tk
from itertools import cycle
mywindow = tk.Tk()
def changeBG():
colors = ["red", "blue", "green", "yellow"]
ciclo = cycle(colors)
siguiente = next(ciclo)
main_btn.config(bg=siguiente)
main_btn = tk.Button(mywindow, text="Change BTN Color", command=changeBG)
main_btn.place(x=50, y=80)
mywindow.mainloop()
import tkinter as tk
import random
mywindow = tk.Tk()
def changeBG():
colors = ["red", "blue", "green" ]
random_colors = random.choice(colors)
main_btn.config(bg = random_colors)
main_btn = tk.Button(mywindow, text="Change BTN Color", command=changeBG)
main_btn.place(x=40, y=50)
mywindow.mainloop()
您需要创建 ciclo
一次。否则你每次都会重新初始化它。
def changeBG():
siguiente = next(ciclo)
main_btn.config(bg=siguiente)
colors = ["red", "blue", "green", "yellow"]
ciclo = cycle(colors)
currentColor 变量在 0 到 3 之间的数字之间循环并更改 BG 的颜色。
mywindow = tk.Tk()
colors = ['red', 'blue', 'green', 'yellow']
currentColor = -1
def changeBG():
global currentColor
currentColor += 1
if currentColor > 3:
currentColor =0
main_btn.config(bg=colors[currentColor])
main_btn = tk.Button(mywindow,text='Change BTN Color',command=lambda:changeBG())
main_btn.place(x=50,y=80)
mywindow.mainloop()
我是新手,每次单击 BTN 时,我都试图找到下一种颜色。 我用函数“random.choice”完成了它并且工作得很好但现在我想获得下一种颜色而不是随机颜色。
import tkinter as tk
from itertools import cycle
mywindow = tk.Tk()
def changeBG():
colors = ["red", "blue", "green", "yellow"]
ciclo = cycle(colors)
siguiente = next(ciclo)
main_btn.config(bg=siguiente)
main_btn = tk.Button(mywindow, text="Change BTN Color", command=changeBG)
main_btn.place(x=50, y=80)
mywindow.mainloop()
import tkinter as tk
import random
mywindow = tk.Tk()
def changeBG():
colors = ["red", "blue", "green" ]
random_colors = random.choice(colors)
main_btn.config(bg = random_colors)
main_btn = tk.Button(mywindow, text="Change BTN Color", command=changeBG)
main_btn.place(x=40, y=50)
mywindow.mainloop()
您需要创建 ciclo
一次。否则你每次都会重新初始化它。
def changeBG():
siguiente = next(ciclo)
main_btn.config(bg=siguiente)
colors = ["red", "blue", "green", "yellow"]
ciclo = cycle(colors)
currentColor 变量在 0 到 3 之间的数字之间循环并更改 BG 的颜色。
mywindow = tk.Tk()
colors = ['red', 'blue', 'green', 'yellow']
currentColor = -1
def changeBG():
global currentColor
currentColor += 1
if currentColor > 3:
currentColor =0
main_btn.config(bg=colors[currentColor])
main_btn = tk.Button(mywindow,text='Change BTN Color',command=lambda:changeBG())
main_btn.place(x=50,y=80)
mywindow.mainloop()