Search code examples
python-3.xtkintertkinter-entry

Entry function not working for simple program


I have difficulty understanding why this very simple piece of code doesn't work. Basically it's supposed to print anything out you type. It runs without errors but when I type something into the entry widget and press the submit button it doesn't print anything out. I'm using Python 3.xx.

from tkinter import *

window = Tk()

def GET():
    typed = e.get()
    print(typed)

e = Entry(window)
e.pack()
b = Button(window, text = "Submit", command = GET())
b.pack()
window.mainloop()

Solution

  • What you need to do is set the command to GET instead of GET(). All you need to do is pass is the reference, not the full function invocation, because that then passes on the return value:

    from tkinter import *
    
    window = Tk()
    
    def GET():
        typed = e.get()
        print(typed)
    
    e = Entry(window)
    e.pack()
    b = Button(window, text = "Submit", command = GET) # GET not GET()
    b.pack()
    window.mainloop()
    

    Now, it will execute GET accordingly. The callback only needs the reference of the function, not a function invocation which will get the return value. This is None in this instance and makes the button do nothing.