Python Tkinter:按钮的颜色变化网格?

时间:2014-10-07 17:23:51

标签: python button tkinter grid

据我所知,你可以制作一个按钮,当你点击Tkinter时可以做一些动作,但是如何点击一个按钮从一种颜色变成另一种颜色呢?然后,从那里,我如何复制该按钮来制作它们的网格?我也会选择一个按钮网格,这些按钮只能从一个角色转换到另一个角色。

1 个答案:

答案 0 :(得分:1)

import Tkinter

color="red"
default_color="white"

def main(n=10):
    window = Tkinter.Tk()
    last_clicked = [None]
    for x in range(n):
        for y in range(n):
            b = Tkinter.Button(window, bg=default_color, activebackground=default_color)
            b.grid(column=x, row=y)
            # creating the callback with "b" as the default parameter bellow "freezes" its value pointing
            # to the button created in each run of the loop.
            b["command"] = lambda b=b: click(b, last_clicked)
    return window

def click(button, last_clicked):
    if last_clicked[0]:
        last_clicked[0]["bg"] = default_color
        last_clicked[0]["activebackground"] = default_color
    button["bg"] = color
    button["activebackground"] = color
    last_clicked[0] = button

w = main()
Tkinter.mainloop()