Search code examples
python-3.xtkinterraspberry-pi3gpioled

Toggle LED Python 3.x tkinter


I'm trying to toggle an LED on and off using a GUI.

When I execute the code I get a blank box just saying "tk" for the title.

import tkinter as tk

class Application(tk.Frame):
    def __init__(self, master=None): 
        super().__init__(master)
        self.pack()
        Label(frame, text='Turn LED ON').grid(row=0, column=0)
        Label(frame, text='Turn LED OFF').grid(row=1, column=0)

        self.button = Button(frame, text='LED 0 ON', command=self.convert0)
        self.button.grid(row=2, columnspan=2)

    def convert0(self, tog=[0]):
        tog[0] = not tog[0]
        if tog[0]:
            self.button.config(text='LED 0 OFF')
        else:
            self.button.config(text='LED 0 ON')

root = tk.Tk()
app = Application(master=root)
app.mainloop()

Solution

  • Your code needs several fixes.

    First off, running it as is gave me the following error:

    NameError: name 'Label' is not defined
    

    And for sure, it is not. What is defined is tk.Label, so let's change those two lines:

    Label(frame, text='Turn LED ON').grid(row=0, column=0)
    Label(frame, text='Turn LED OFF').grid(row=1, column=0)
    

    into:

    tk.Label(frame, text='Turn LED ON').grid(row=0, column=0)
    tk.Label(frame, text='Turn LED OFF').grid(row=1, column=0)
    

    Now, I'm raised the following error:

    NameError: name 'frame' is not defined
    

    And sure enough, it isn't either. You're probably refering to the fact that the Application class extends the tk.Frame class. Well, that's true, but that doesn't tell us what frame is. I assume that frame means "the instance, but considered as a Frame instance". In this case, self is enough (and it's actually what is needed). So here we go, the following three lines:

    tk.Label(frame, text='Turn LED ON').grid(row=0, column=0)
    tk.Label(frame, text='Turn LED OFF').grid(row=1, column=0)
    
    self.button = Button(frame, text='LED 0 ON', command=self.convert0)    
    

    become:

    tk.Label(self, text='Turn LED ON').grid(row=0, column=0)
    tk.Label(self, text='Turn LED OFF').grid(row=1, column=0)
    
    self.button = Button(self, text='LED 0 ON', command=self.convert0) 
    

    Now, I'm told that

    NameError: name 'Button' is not defined
    

    I'm sure you're starting to understand the point. So let's replace Button by tk.Button:

    self.button = tk.Button(self, text='LED 0 ON', command=self.convert0)
    

    And here you go, the window is displayed, with two labels and one nice button, whose text changes when clicked.