2014-10-07 187 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