2016-07-19 138 views
1
try: 
    #Python 2 
    import Tkinter as tk 
except ImportError: 
    #Python 3 
    import tkinter as tk 

def flip_switch(canv_obj, btn_text): 
    if btn_text == 'on': 
     canv_obj.config(bg="#F1F584") 
    else: 
     canv_obj.config(bg="#000000") 

main_window = tk.Tk() 

light = tk.Canvas(main_window, bg="#000000", width=100, height=50) 
light.pack() 

on_btn = tk.Button(main_window, text="ON", command=flip_switch(light, 'on')) 
on_btn.pack() 

off_btn = tk.Button(main_window, text="OFF", command=flip_switch(light, 'off')) 
off_btn.pack() 

main_window.mainloop() 

這個小代碼用作光開關應用,而是按下ON按鈕時,沒有任何反應 - 不是連的錯誤消息。請糾正我出錯的地方。按下按鈕時,什麼都沒有發生。甚至沒有錯誤消息

回答

2

您應該將參數傳遞給command參數,但是您正在運行該函數並傳遞返回值(即None)。嘗試添加下面的輔助功能:

def light_on(): 
    flip_switch(light, 'on') 

def light_off(): 
    flip_switch(light, 'off') 

然後初始化Buttons這樣的:

on_btn = tk.Button(main_window, text="ON", command=light_on) 
off_btn = tk.Button(main_window, text="OFF", command=light_off) 

另一種方法是使用內嵌到lambda寫那些輔助方法:

on_btn = tk.Button(main_window, text="ON", command=lambda: flip_switch(light, 'on')) 
off_btn = tk.Button(main_window, text="OFF", command=lambda: flip_switch(light, 'off')) 
相關問題