Tkinter binding button press to functions

Question:

I have a UI with an entry, and a button that deploys multiple functions using said entry.

ent = tk.Entry(frm_top, textvariable=entry_input)     
btn_confirm = tk.Button(frm_inner_bot, text="Confirm", width=25, height=2, command=lambda:
[main.save_template(entry_input.get(),filedialog.askdirectory()),update_main_window(label, listbox), create_template_window.destroy()])

I would like to be able to press from the entry and do the same functions as the button press does, however im not managing to do so.

I’ve attempted using the bind command and simply fill it with the lambda but it didn’t work.

ent.bind('<Return>', lambda:[main.save_template(entry_input.get(),filedialog.askdirectory()),update_main_window(label, listbox), create_template_window.destroy()])

I’ve also tried invoking the button press, however it just does everything at once instead of 1 action at a time like in the button press.

ent.bind('<Return>', btn_confirm.invoke())

I’d appreciate if anyone could explain to me where i went wrong, and how to solve my issue on the matter.

Read multiple articles and tutorials on the matter, however couldn’t find one that addresses multiple function deployment from the binding.

Asked By: Alexey-Vi

||

Answers:

You should bind the parent window of the entry widgets with ‘Return’ and function like how you map the button with the function. For instance..

from tkinter import *

def function to be triggered(*e):
    user_entry = ent.get()
    # Do something


root = Tk()
root.geometry('300x200')
ent = Entry(root)
ent.pack()

root.bind('<Return>', function_to_be_triggered)
btn = Button(root, command=function_to_be_triggered)
btn.pack()

root.mainloop()
Answered By: Suramuthu R

For your case, the line ent.bind('<Return>', btn_confirm.invoke()) will execute btn_confirm.invoke() immediately and then assign the result (a tuple) as the binding callback.

The line should be ent.bind('<Return>', lambda e: btn_confirm.invoke()) instead.

Also it is not a good practice to call multiple functions inside a lambda. It is better to put those multiple functions inside another function:

def func():
    main.save_template(entry_input.get(), filedialog.askdirectory())
    update_main_window(label, listbox)
    create_template_window.destroy()

ent = tk.Entry(frm_top, textvariable=entry_input)
ent.bind("<Return>", lambda e: func())
btn_confirm = tk.Button(frm_inner_bot, text="Confirm", width=25, height=2,
                        command=func)
Answered By: acw1668