您可以通过实现一个生成器来解决这个问题,该生成器每次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每次调用时都会从给定序列中返回一个随机元素。