Beginner - GUI switch button

May I ask for a little help? I created a GUI with a toggle button that switches the LED indicator, the LED is off.

Now, I would like to add code to change the button text, as it switches between the two states.

I looked through a few examples, but I can’t figure out how and where to add the code so that the button text also switches.

Thanks for any help.

My code is ....

# Idle 07_02_LED ON using GUI
from time import sleep

from Tkinter import *

class App:

    def __init__(self, master): 
        frame = Frame(master)
        frame.pack()
        Label(frame, text='Turn LED ON').grid(row=0, column=0)

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

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


    def convert0(self, tog=[0]):

        tog[0] = not tog[0]
        if tog[0]:
        print('LED 0 OFF')

        else:
        print('LED 0 ON')

root = Tk()

root.wm_title('LED on & off program')

app = App(root)

root.mainloop()
+4
source share
1 answer

You need to do two things:

script. , :

# Idle 07_02_LED ON using GUI
from time import sleep

from Tkinter import *

class App:

    def __init__(self, master): 
        frame = Frame(master)
        frame.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()

root.wm_title('LED on & off program')

app = App(root)

root.mainloop()
+4

All Articles