0

The code is below from this post:

Why is Tkinter Entry's get function returning nothing?

The argument in the return_entry is 'en' and when I deleted it out it says a positional argument is missing. What is the def return_entry('en') mean and why does it only work with it.

Why cant i just use:

def return_entry():

The en argument makes no sense to me...

from tkinter import *    
master = Tk()

def return_entry(en):
    content = entry.get()
    print(content)



Label(master, text="Input: ").grid(row=0, sticky=W)

entry = Entry(master)
entry.grid(row=0, column=1)

# Connect the entry with the return button
entry.bind('<Return>', return_entry) 

mainloop()

Error:

 TypeError: return_entry() takes 0 positional arguments but 1 was given

Only throws an error when I remove en and hit enter after I enter input in the entry box.

SF12 Study
  • 375
  • 4
  • 18
  • 1
    All Tkinter event bindings receive a single parameter when they are invoked, which contains details about the event. It's not particularly useful in your case, since you are binding to such a specific event, but imagine if you had bound to an arbitrary keypress - without that parameter, you'd have no way to tell what key had been pressed. – jasonharper Aug 23 '19 at 00:24

1 Answers1

3

bind expects function which can get argument to send event to this function - and it will run it as return_entry(event). And this is why you can't use function without argument.

You can even use this event to get access to entry - so you can assing the same function to different entries and ifunction will get text from correct entry

def return_entry(event):
    content = event.widget.get()
    print(content)

Sometimes we may want to use the same function with command= which doesn't send event to function and then we can use event=None but then we can't use event inside function

def return_entry(event=None):
    content = entry.get()
    print(content)

entry.bind('<Return>', return_entry)

tk.Button(..., command=return_entry)

Working examples:

Function binded to two entries:

import tkinter as tk

def return_entry(event):
    content = event.widget.get()
    print(content)

root = tk.Tk()

entry1 = tk.Entry(root)
entry1.pack()

entry1.bind('<Return>', return_entry)

entry2 = tk.Entry(root)
entry2.pack()

entry2.bind('<Return>', return_entry)

root.mainloop()

Function assigned to Entry and Button

import tkinter as tk

def return_entry(event=None):
    content = entry.get()
    print(content)

root = tk.Tk()

entry = tk.Entry(root)
entry.pack()

entry.bind('<Return>', return_entry)

button = tk.Button(root, text='OK', command=return_entry)
button.pack()

root.mainloop()
furas
  • 134,197
  • 12
  • 106
  • 148