1

I have a toplevel window that pops up off of root. It builds all the necessary widgetes on creation, which I then want to be filled and submitted. The problem is, all the variables I define in the new window go out of scope when I call the submit command. I really don't want to call everything a global because this window will be destroyed and recreated several times.

Here's my relevent code:

def add_item():  
   window = Toplevel(root)
   window.title("Add Item")
   window.geometry("400x150")

   name = Entry(window, width=40)
   name.grid(row=0, column=1, sticky=W)
   name.insert(0, "Name")

   Button(window,text="Submit Item",command=submit_item).place(relx=0.5,rely=0.9,anchor=S)

def submit_item():
   print(name.get())

I end up with the error:

    print(name.get())
NameError: name 'name' is not defined
Elle
  • 21
  • 1
  • 3
  • I have several (10+) variables that I'd need to return. I suppose I could make a list of all my widgets but I was hoping there'd be a better way to maintain scope in a command function? – Elle Jan 20 '18 at 20:07
  • 3
    Place all GUI functions in a class. This is a common practice. – DYZ Jan 20 '18 at 20:08
  • 2
    @DYZ Yep, good idea. I was just about to say the same thing. – Christian Dean Jan 20 '18 at 20:08
  • You may want to see https://stackoverflow.com/q/17466561/7032856 for better structuring your tkinter scripts. – Nae Jan 20 '18 at 20:09
  • 1
    Possible duplicate of [Best way to structure a tkinter application](https://stackoverflow.com/questions/17466561/best-way-to-structure-a-tkinter-application) – Christian Dean Jan 20 '18 at 20:10
  • Alright @Elle, happy programming :-) – Christian Dean Jan 20 '18 at 20:14
  • 1
    This is not a tkinter problem, you're asking about a fundamental aspect of python. You should start by reading some python documentation and/or work through a python tutorial. – Bryan Oakley Jan 20 '18 at 21:44
  • Possible duplicate of [How does Python print a variable that is out of scope](https://stackoverflow.com/questions/39438573/how-does-python-print-a-variable-that-is-out-of-scope) – Hippolippo Jan 21 '18 at 00:32

0 Answers0