Button switching using python (Tkinter)

Multi tool use
Button switching using python (Tkinter)
What I'm trying to do is to switch buttons, basically.
When button 1 is pressed it gets destroyed and then button 2 launches.
I'm having an error, here's the code.
from Tkinter import *
root = Tk()
root.title('TEST')
def D1():
B.destroy()
Launch2()
def D2():
B2.destroy()
Launch1()
def Launch1():
B = Button (root, text = 'BUTTON 1', command = D1)
B.pack()
def Launch2():
B2 = Button (root, text = 'BUTTON 2', command = D2)
B2.pack()
Launch1()
mainloop()
Error :
Exception in Tkinter callback
Traceback (most recent call last):
File "C:Python27liblib-tkTkinter.py", line 1541, in __call__
return self.func(*args)
File "C:UsersyouseDesktopTkinter Testing GUI.py", line 5, in D1
B.destroy()
NameError: global name 'B' is not defined
B
2 Answers
2
Just add the lines, global B and global B2 to the code in the following way:
def Launch1():
global B # Make B a global variable
B = Button (root, text = 'BUTTON 1', command = D1)
B.pack()
def Launch2():
global B2 # Make B2 a global variable
B2 = Button (root, text = 'BUTTON 2', command = D2)
B2.pack()
The program now works perfectly for me.
The variable B in the function Launch1 is defined locally only in that function
The same is true for B2.
Hence the D1 function does not have access to B and D2 does not have access to B2.
You need to find a way to make function D see variable B
One solution is to create B outside the functions then use global B in the two functions launch1 and D - then do the same for B2
This is not a recommended solution, normally you would have a class defined that could hold B, B2 and the four functions then there would be no need for global variables
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
The error is telling the truth. There's nowhere in your code where you're creating a global variable named
B
.– Bryan Oakley
Jul 1 at 23:05