Search code examples
pythontkinterboxtkinter-entry

Tkinter store entry box value as value for other file


This is my first python personal project. I am wanting to use Tkinter to create a window (GUARDIAN LOCATOR) that asks the user to input a value (enter sailor guardian) into the entry box. The rest of the program is dependent on what the user types in the entry box as I will be having if/else statements reacting to the sailor guardian entered.

The issue I am having is storing what is entered in the entry box as a variable to use in my main file for the if/else statements. I can get the value to print to the prompt window, but I haven't been able to store it successfully to a global variable.

My Tkinter window is in it's own class.

I have tried many different ways of doing this based on similar issues from stackoverflow, but I am getting an error every time. This is my base code that still produces the error.

Class file with the Tkinter window

class GuardianLocator:

def __init__(self, master):
    frame = Frame(master)
    frame.grid()
    master.title("GUARDIAN LOCATOR")

    self.locator_label = Label(frame, text="Which Sailor Guardian are you looking for?", width=40, height=2)
    self.locator_label.grid()

    self.entry = Entry(frame)
    self.entry.grid()

    self.button1 = Button(frame, text="Search", command=self.guardian_name, pady=2)
    self.button1.grid()

def guardian_name(self):
    print(self.entry.get())

and in my main working file

root = Tk()
locator = guardian_locator.GuardianLocator(root)

root.mainloop()

This is my test loop to see if it's working.

if locator.guardian_input() is "Sailor Moon":
    print("hi")
else:
    print("no")

Solution

  • Not sure exactly how your code is organized and where is your "test loop" located, but I assume it is after root.mainloop(). Thus the script can be as follows:

    from tkinter import *
    
    
    class GuardianLocator:
    
        def __init__(self, master):
            self._name = "" 
            frame = Frame(master)
            frame.grid()
            master.title("GUARDIAN LOCATOR")
    
            self.locator_label = Label(frame, text="Which Sailor Guardian are you looking for?", width=40, height=2)
            self.locator_label.grid()
    
            self.entry = Entry(frame)
            self.entry.grid()
    
            self.button1 = Button(frame, text="Search", command=self.guardian_name, pady=2)
            self.button1.grid()
    
        def guardian_name(self):
            self._name = self.entry.get()
            print(self.entry.get())
    
    
    root = Tk()
    locator = GuardianLocator(root)
    
    root.mainloop()
    
    # this will be executed after the root window is closed.
    print("Name is", locator._name)   
    

    Please note self._name = "" in the constructor. This instance variable can be used to store the name provided in your GuardianLocator window.