The code:
from tkinter import *
def show (A, B, C, D):
if A == "Large":
Label1 = Label(root, text=A).pack()
if B == "Medium":
Label1 = Label(root, text=B).pack()
if C == "Small":
Label1 = Label(root, text=C).pack()
if D == "Infinitesimal":
Label1 = Label(root, text=D).pack()
def clear ():
Label1.destroy()
root = Tk()
root.geometry("500x500 200 200")
var1 = StringVar()
var2 = StringVar()
var3 = StringVar()
var4 = StringVar()
a =Checkbutton(root, text="Large?", variable=var1, onvalue="Large")
a.deselect()
a.pack()
b =Checkbutton(root, text="Medium?", variable=var2, onvalue="Medium")
b.deselect()
b.pack()
c =Checkbutton(root, text="Small?", variable=var3, onvalue="Small")
c.deselect()
c.pack()
d =Checkbutton(root, text="Infinitesimal?", variable=var4, onvalue="Infinitesimal")
d.deselect()
d.pack()
W = Button(root, text="Submit", command=lambda: show(var1.get(), var2.get(), var3.get(), var4.get(), )).pack()
x = Button(root, text="Clear", command=clear).pack()
root.mainloop()
The initial checked list of items will post, but, then, suppose one wants to clear the screen using the clear button. That's when I run into the following error.
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "<ipython-input-55-b81bc2ffe1d0>", line 22, in clear
Label1.destroy()
NameError: name 'Label1' is not defined
My concern isnt so much in just fixing this one script, but I am interested in understanding what I did wrong and how to handle this type of error.
why is not the computer identifying 'Label1' as defined?
CodePudding user response:
In the show()
function, at the very start of it, add global Label1
.
Also, if you want: What are Global and Local variables in Python?