如何将itertools.cycle与多个对象一起使用?

时间:2015-11-11 15:56:40

标签: python python-3.x tkinter itertools

我试图通过itertools.cycle迭代器中定义的颜色在Tkinter中按下时循环按钮的颜色:

colour=itertools.cycle('blue', 'green', 'orange', 'red', 'yellow', 'white')

def changeColour(button):
    button.configure(bg = next(colour))

LT = Button(root, width=16, height=8, bg = 'white', command=lambda: changeColour(LT))
LT.place(x=10, y=10)

LM = Button(root, width=16, height=8, bg = 'white', command=lambda: changeColour(LM))
LM.place(x=10, y=150)

LB = Button(root, width=16, height=8, bg = 'white', command=lambda: changeColour(LB))
LB.place(x=10, y=290)

但是,按下每个按钮会影响下一次按下按钮的迭代中的起始位置,这意味着每个按钮将在分配给之前单击的按钮后跳转到next(colour)的值。我尝试让每个按钮执行与其他按钮的当前颜色无关的完整循环背景颜色。我怎么能做到这一点?

2 个答案:

答案 0 :(得分:2)

如果您希望每个按钮独立,则需要为每个按钮分别设置cycle。一种方法是创建一个函数工厂来构建你需要调用的函数:

COLOURS = ('blue', 'green', 'orange', 'red', 'yellow', 'white')

def colour_changer(button, colours=COLOURS):
    """Creates a callback to change the colour of the button."""
    colour_cycle = itertools.cycle(colours)
    def command():
        """The callback to change a single button's colour."""
        button.configure(bg=next(colour_cycle))
    return command

然后在创建每个按钮后调用它:

LT = Button(root, width=16, height=8, bg = 'white')
LT.configure(command=colour_changer(LT))

您还可以查看绑定,它会将按钮传递给您的回调。

答案 1 :(得分:0)

每个按钮都知道它当前的背景颜色。以下使用字典以循环方式将当前颜色映射到下一个颜色。

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})