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按钮时,没有任何反应 - 甚至不是错误消息。请纠正我出错的地方。
答案 0 :(得分: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'))