Python 当按下按钮时,什么也没有发生。甚至没有错误消息
这个小代码充当一个灯光开关应用程序,但是当按下ON按钮时,什么也没有发生,甚至错误消息也没有发生。请纠正我的错误。您应该将函数引用传递给Python 当按下按钮时,什么也没有发生。甚至没有错误消息,python,tkinter,Python,Tkinter,这个小代码充当一个灯光开关应用程序,但是当按下ON按钮时,什么也没有发生,甚至错误消息也没有发生。请纠正我的错误。您应该将函数引用传递给命令参数,但您当前正在运行该函数并传递返回值(即无)。尝试添加以下帮助器函数: try: #Python 2 import Tkinter as tk except ImportError: #Python 3 import tkinter as tk def flip_switch(canv_obj, btn_text):
命令
参数,但您当前正在运行该函数并传递返回值(即无
)。尝试添加以下帮助器函数:
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()
然后初始化按钮,如下所示:
def light_on():
flip_switch(light, 'on')
def light_off():
flip_switch(light, 'off')
另一种方法是使用lambda
内联编写这些helper方法:
on_btn = tk.Button(main_window, text="ON", command=light_on)
off_btn = tk.Button(main_window, text="OFF", command=light_off)
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'))