Reputation: 125
Can i ask for a little help please? I've created a GUI with a toggle button which toggles the LED ON, LED OFF.
What i would like to do now is add some code to change the text of the button as it toggles between the two states.
I've looked up some examples but I can't quite see how, or where, to add the code to make the button text toggle as well.
Thanks for any help.
My code....
# 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()
Upvotes: 5
Views: 6908
Reputation:
You need to do two things:
Define the button as self.button
so that it becomes an instance attribute of App
. That way, you can access it inside convert0
through self
.
Use Tkinter.Button.config
to update the button's text.
Below is a fixed version of the script. I put the stuff I changed in comment boxes:
# 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()
Upvotes: 4