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

This little code acts as a light switch application but when the ON button is pressed, nothing happens -not even the error messages. Please correct me where I had gone wrong.

Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130

1 Answers1

2

You should pass a function reference to the command argument but you are currently running the function and passing the return value (which is None) instead. Try adding the following helper functions:

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

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

then initialize your Buttons like this:

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

Another method would be to write those helper methods inline using 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'))
Selcuk
  • 57,004
  • 12
  • 102
  • 110