0

我想知道如何更改下面的代码以使其能够打印出语句“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()
4

1 回答 1

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每次调用时都会从给定序列中返回一个随机元素。

于 2013-09-10T13:38:47.637 回答