我想知道我将如何更改下面的代码以使其能够打印出“Hell yeah!”的声明。每次单击按钮,但每次都以不同的颜色。我一直在考虑采取不同的方式去做,但它似乎永远不会成功。有什么帮助吗?
from tkinter import *
master = Tk()
def b1():
jl = Label(master, text="Hell yeah!", fg="blue", bd = 3).pack()
b = Button(master, text="Press me!", command=b1, padx = 5, pady = 5, bg="grey")
b.pack(fill=BOTH, expand=1)
mainloop()
答案 0 :(得分:1)
你可以通过实现一个生成器来解决这个问题,该生成器每次调用next
时都会从颜色集合中返回一个值:
from itertools import repeat
def get_color_generator():
# This will return a tuple with the colors on each iteration
COLORS = repeat(("blue", "red", "yellow"))
# This will never terminate ('repeat' without a second argument
# creates an endless generator)
for color_set in COLORS:
for color in color_set:
yield color
color_generator = get_color_generator()
def b1():
bl = Label(master, text="Hell yeah!", fg=next(color_generator), bd = 3).pack()
如果颜色的顺序无关紧要,那就更容易了:
from random import choice
COLORS = ("blue", "red", "yellow")
def b1():
bl = Label(master, text="Hell yeah!", fg=choice(COLORS), bd = 3).pack()
每次调用时,random.choice都会返回给定序列中的随机元素。