2014-03-31 53 views
0

我有下面的代碼有問題:的Python的Tkinter如何改變背景顏色,而支架是活動

def __init__(self): 
    window = Tkinter.Tk() 
    window.minsize(600,600) 
    window.maxsize(600,600) 
    window.title("test") 

    #window.iconbitmap('sample.ico') 

    menu_bar = Tkinter.Menu(window) 

    change_color_option = Tkinter.Menu(menu_bar, tearoff=0) 
    change_color_option.add_command(label = "Red", command = self.color_change(1, window)) 
    change_color_option.add_command(label = "Blue", command = self.color_change(2, window)) 
    change_color_option.add_command(label = "Yellow", command = self.color_change(3, window)) 
    change_color_option.add_command(label = "Green", command = self.color_change(4, window)) 
    change_color_option.add_command(label = "Purple", command = self.color_change(5, window)) 
    change_color_option.add_command(label = "Brown", command = self.color_change(6, window)) 

    file_menu_item = Tkinter.Menu(menu_bar, tearoff=0) 
    file_menu_item.add_command(label = "Quit", command = window.quit) 

    option_menu_item = Tkinter.Menu(menu_bar, tearoff=0) 
    option_menu_item.add_cascade(label = "change color", menu = change_color_option) 


    menu_bar.add_cascade(label="File", menu=file_menu_item) 
    menu_bar.add_cascade(label="Options", menu=option_menu_item) 

    window.config(menu=menu_bar) 

    window.mainloop() 

def color_change(self, color, window): 
    if color == 1: 
     window.configure(background = "#CC0000") 
    elif color == 2: 
     window.configure(background = "#0000CC") 
    elif color == 3: 
     window.configure(background = "#FFFF00") 
    elif color == 4: 
     window.configure(background = "#336600") 
    elif color == 5: 
     window.configure(background = "#660099") 
    elif color == 6: 
     window.configure(background = "#663300") 

但我的問題是,該窗口將採取最後一種顏色(#663300),它不會即使我按菜單按鈕更改顏色也會改變。我必須再次運行mainloop,這並不是每次我改變顏色時都想做的事情。有沒有辦法解決它?

回答

1

要使用回調命令傳遞參數,您需要使用lambda表達式。否則,Tkinter將在構建小部件時執行回調,這就是爲什麼它直接前往最後一個值,因爲這是流程最後一個流程。

格式的lambda表達式是這樣的:

change_color_option.add_command(label = "Red", command = lambda: self.color_change(1, window)) 

更多信息:http://effbot.org/zone/tkinter-callbacks.htm

+0

哇,謝謝,你統治! ;) –