Search code examples
pythonbuttontkintertkinter-entry

Python Tkinter Button/Entry combination


I've been experimenting with Tkinter, and I have a set-up where I have an entry box and then below it two buttons (Close and OK). When close is clicked, the frame is destroyed. I want it to return whatever is in the entry box at the time and then destroy the frame. I am just at a loss for how to do this.

This is a portion of what I have (where f is my frame):

class App:
    def DoThis(self):
        #Earlier code that's not related to the question
        v=StringVar()
        e=Entry(f,textvariable=v)
        buttonA=Button(f,text="Cancel",command=root.destroy)
        buttonB=Button(f,text="OK")

Also, please note that I want to RETURN the string to the calling function, not just immediately print it.

I want:

print App().DoThis() #to print what was in the entry box
#at the time of OK being clicked

Solution

  • What you ask is, for all intents and purposes, impossible. The function DoThis will return before the GUI even displays on the screen.

    That being said, such a thing is possible, though highly unusual. It's a bit like asking how you can haul a bale of hay across a muddy field in a Ferrari.

    If you just plan on popping up a window once, you can get by with something like the following:

    import Tkinter as tk
    
    class MyApp(tk.Tk):
        def __init__(self):
            tk.Tk.__init__(self)
            self.entry = tk.Entry(self)
            self.entry.pack()
            close_button = tk.Button(self, text="Close", command=self.close)
            close_button.pack()
            self.string = ""
    
        def close(self):
            global result
            self.string = self.entry.get()
            self.destroy()
    
        def mainloop(self):
            tk.Tk.mainloop(self)
            return self.string
    
    print "enter a string in the GUI"
    app = MyApp()
    result = app.mainloop()
    print "you entered:", result
    

    If you are going to open the window more than once you're probably not going to have much luck because, again, this just isn't how Tkinter is designed to be used.