2014-10-07 191 views
-1

我知道你可以制作一个按钮,当点击Tkinter时可以执行一些操作,但是我怎样才能制作一个按钮,当点击时从一种颜色变成另一种颜色?那么,从那以后,我如何复制那个按钮来制作它们的网格呢?我也会解决一个从一个角色变为另一个角色的按钮。Python Tkinter:颜色变化的按钮网格?

回答

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() 
+0

非常感谢!即使在我选择了另一个按钮之后,是否有任何方法可以使按钮保持活动状态。我真正想要的是当我点击它们时可以在两种颜色之间改变的按钮。如果你能提供帮助,请尽量指出我正确的方向,而不是给我全部答案。我仍然在学习,想要自己尝试一些东西! – LukeK15 2014-10-07 22:45:25