Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 当按下按钮时,什么也没有发生。甚至没有错误消息_Python_Tkinter - Fatal编程技术网

Python 当按下按钮时,什么也没有发生。甚至没有错误消息

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):

这个小代码充当一个灯光开关应用程序,但是当按下ON按钮时,什么也没有发生,甚至错误消息也没有发生。请纠正我的错误。

您应该将函数引用传递给
命令
参数,但您当前正在运行该函数并传递返回值(即
)。尝试添加以下帮助器函数:

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'))