Search code examples
pythontkintertkinter-entrytkinter-button

Tkinter binding button press to functions


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.


Solution

  • 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)