Home > front end >  How can I fix this Error (Entry1 not defined)
How can I fix this Error (Entry1 not defined)

Time:01-31

I just started coding with Python and I can't find out how to fix the Error (NameError: name 'entry1' is not defined)

def forrangeright():
    entry1 = ttk.Entry(root, width=40)
    entry1.pack(padx=10, pady=10, side="bottom")
    confirmi_button = ttk.Button(root, text="Confirm", command=confirmichars)
    confirmi_button.pack(padx=10, side="bottom", fill="x")


def confirmichars():
    customichars = entry1.get() < --- Error
    Herre
    print(customichars)

CodePudding user response:

The issue here is with scope.

A variable created inside a function belongs to the local scope of that function, and can only be used inside that function. https://www.w3schools.com/python/python_scope.asp

Here you define entry1 in the local scope of the forrangerright() function meaning that outside of that function entry1 is undefined.

You can either define entry1 outside of a function as a global variable (bad practice)

Or return entry1 from the forrangerright() function and pass it to confirmichars()

Here is an example:

def forrangeright():
    entry1 = ttk.Entry(root, width=40)
    entry1.pack(padx=10, pady=10, side="bottom")
    confirmi_button = ttk.Button(root, text="Confirm", command=confirmichars)
    confirmi_button.pack(padx=10, side="bottom", fill="x")
    return entry1

def confirmichars():
        entry1 = forrangeright()
        customichars = entry1.get()   <--- Error Herre
        print(customichars)

or pass entry1 as an argument

def forrangeright():
    entry1 = ttk.Entry(root, width=40)
    entry1.pack(padx=10, pady=10, side="bottom")
    confirmi_button = ttk.Button(root, text="Confirm", command=confirmichars)
    confirmi_button.pack(padx=10, side="bottom", fill="x")
    return entry1

def confirmichars(entry1):
        customichars = entry1.get()   <--- Error Herre
        print(customichars)

CodePudding user response:

entry1.get() is set in your function forrangeright() but not in confirmichars()

If you want to access to entry1.get() in confirmichars() you need to add entry1.get() in the function parameter like this:

def confirmichars(entry1):
    customichars = entry1.get() < --- No Error Herre
    print(customichars)

Then you need to pass the argument so you can add a return to your function forrangeright() like this:

def forrangeright():
    entry1 = ttk.Entry(root, width=40)
    entry1.pack(padx=10, pady=10, side="bottom")
    confirmi_button = ttk.Button(root, text="Confirm", command=confirmichars)
    confirmi_button.pack(padx=10, side="bottom", fill="x")
    return entry1

Finally you can call your function confirmichars(entry1) like this:

entry1 = forrangeright()
confirmichars(entry1)
  •  Tags:  
  • Related