Skip to content
Advertisement

If I created widgets in one function, how can I access them in another function using Python Tkinter?

this is my first project using Tkinter so please excuse me if the question is very simple to solve. Depending on what option the user chooses from a dropdown, I call a function that creates and places certain widgets (e.g. an entry) on a frame. Then, when another button is pushed I want to access the text inside this entry. However, this seems to be giving me errors (saying that the widget is undefined) because I want to access a widget which I create when a function is called.

An obvious solution I see is to create all possible widgets I want to use outside the function, and only place them when the function is called. This seems quite sloppy and creates many more issues. Is there another fix?

Thanks in advance!

This is the function where I create and place the widgets on the frame.

def loadBook():
    print("book is loaded")
    #Authors
    labelAuth1 = tk.Label(frame, text="Author 1 Name:")
    entryAuth1 = tk.Entry(frame)

    labelAuth1.place(relwidth=0.23, relheight=0.08, rely=0.1)
    entryAuth1.place(relheight=0.08, relwidth=0.18, relx=0.3, rely=0.1)

This is a snippet of a function which uses input from the entry widget I created above:

def isBook():
    if len(entryAuthSur1.get())==0:
        pass
    else:
        bookString = ""
        bookString += entryAuthSur1.get()

When the second function executes, I get a runtime error that entryAuthSur1 is not defined.

Advertisement

Answer

All variables inside functions are local. That means that it is deleted after the function call ends. As your variable (entryAuth1) wasn’t global so it only existed inside the function and was deleted when the loadBook function ended. This is the working code:

import tkinter as tk

# Making a window for the widgets
root = tk.Tk()


def loadBook():
    global entryAuth1 # make the entry global so all functions can access it
    print("book is loaded")
    #Authors
    labelAuth1 = tk.Label(root, text="Author 1 Name:")
    entryAuth1 = tk.Entry(root)
    # I will check if the user presses the enter key to run the second function
    entryAuth1.bind("<Return>", lambda e: isBook())

    labelAuth1.pack()
    entryAuth1.pack()

def isBook():
    global entryAuth1 # make the entry global so all functions can access it

    # Here you had `entryAuthSur1` but I guess it is the same as `entryAuth1`
    if len(entryAuth1.get())==0:
        pass
    else:
        bookString = ""
        bookString += entryAuth1.get()
        print(bookString) # I am going to print the result to the screen


# Call the first function
loadBook()

root.mainloop()
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement