Returning a Parameter from a Python Tkinter Pop-Up-Window Entry

Question:

I am trying to create a pop up window with Tkinter where I can enter values with an entry window to use them in the main code.

Currently I am trying to simply output the input. I can’t get it to work, does anyone have an idea how I can solve this problem?
Here is a small snippet of my code. I have not used the variables from the functions anywhere else in the code.

root = Tk()  # set up GUI
menuleiste = Menu(root) #menu bar


def take_over_Temp():
    #Tempstring = str(eKnopf.get())
    print(eKnopf.get())
    print("got it")


def open_popup():
   #global eKnopf
   top= Toplevel(root)
   top.geometry("750x250")
   top.title("Child Window")
   #Label(top, text= "Hello World!", font=('Mistral 18 bold')).place(x=150,y=80)
   eKnopf = Entry(top, bd = 5).place(x=10,y=100, width=100)
   button_take_Temp = Button(top, text='Set Temperature', fg="red", command=take_over_Temp)
   button_take_Temp.place(x=10, y=150, width=100)
   return(eKnopf)


optionen_menu.add_command(label="Offset", command = open_popup)

When I try it like this I get this Error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.9/tkinter/__init__.py", line 1892, in __call__
    return self.func(*args)
  File "/home/user/FAC.py", line 724, in take_over_Temp
    print(eKnopf.get())
NameError: name 'eKnopf' is not defined
Asked By: Paulina F

||

Answers:

You need to pass in eKnopf as a parameter to take_over_Temp()

eKnopf = Entry(top, bd = 5)
eKnopf.place(x=10, y=100, width=100)
button_take_Temp = Button(
    top,
    text='Set Temperature', 
    fg="red", 
    # use a lambda to pass `eKnopf` as an argument 
    command=lambda ent=eKnopf: take_over_Temp(ent)
)

Then modify take_over_Temp to accept and use that value:

def take_over_Temp(ent):
    print(ent.get())

FYI, the error you’re seeing is essentially saying that the function take_over_Temp doesn’t know what eKnopf is because it doesn’t exist within the scope of the function.

Answered By: JRiggles