NameError: name 'lab2' is not defined

Question:

I have a problem, when I am creating a Label in function (def), and after I am trying to destroy this Label, using other fucntion (def), it says, that lab2 is not defined

from tkinter import*

root=Tk()
root.geometry("500x300")

def com1():
    global lab, but
    lab.destroy()
    but.destroy()
    lab=Label(text="Label 2")
    lab.place(x=237, y=27)
    but=Button(text="Go to first screen", command=com2)
    but.place(x=200, y=57)
    lab2=Label(text="Label 3")
    lab2.place(x=220, y=107)

def com2():
    global lab, but
    lab.destroy()
    but.destroy()
    lab2.destroy()
    lab=Label(text="Label")
    lab.place(x=237, y=27)
    but=Button(text="Go to second screen", command=com1)
    but.place(x=200, y=57)


lab=Label(text="Label")
lab.place(x=237, y=27)

but=Button(text="Go to second screen", command=com1)
but.place(x=200, y=57)

root.mainloop()

How can i create a Label if fucntion(def) and make it so, that other functions(defs) could see it and, for example, destroy it

Asked By: Sk1rry

||

Answers:

just global lab2:

from tkinter import*

root=Tk()
root.geometry("500x300")

def com1():
    global lab, but,lab2
    lab.destroy()
    but.destroy()
    lab=Label(text="Label 2")
    lab.place(x=237, y=27)
    but=Button(text="Go to first screen", command=com2)
    but.place(x=200, y=57)
    lab2=Label(text="Label 3")
    lab2.place(x=220, y=107)

def com2():
    global lab, but,lab2
    lab.destroy()
    but.destroy()
    lab2.destroy()
    lab=Label(text="Label")
    lab.place(x=237, y=27)
    but=Button(text="Go to second screen", command=com1)
    but.place(x=200, y=57)


lab=Label(text="Label")
lab.place(x=237, y=27)

but=Button(text="Go to second screen", command=com1)
but.place(x=200, y=57)

root.mainloop()

have fun 🙂

Answered By: nariman zaeim
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.