bind enter key to run a command in tkinter label

I am trying to make a simple find and replace widget in tkinter. I can press the button "RegexReplace" and it works good without any problems.

In this widget, we first type if label1, then label2, what I want is when I type text to be replaced in label called "To" and press Return Key, I want the app to do the find and replace without need to pressing the button "RegexReplace".

When we are typing in "To" label,
if we press "Enter" key, run the function "find_and_replace"
if we press "ctrl+Enter" key run the function "find_and_replace".

Basically, I don’t want to press "RegexReplace" button and when I hit enter after typing "To" field, I want the command to run.

My attempts

l_to.bind("<Return>",  lambda x=[e_from,e_to]: find_and_replace(x[0],x[1]) ) # did not work


import tkinter as tk
from tkinter import ttk,messagebox

win = tk.Tk()
def find_and_replace(entry_from,entry_to):       
    # Get variables
    str_from = entry_from.get()
    str_to = entry_to.get()
    s = 'Quick brown fox jumped.'
    out = s.replace(str_from, str_to)
    tk.Label(win, text=out).pack(pady=4)

f = tk.Frame(win,height=200, width=200)
f.grid(row=0,column=0,padx=20, pady=20)
f.pack(fill="both", expand="yes")
# label frame: Find and Replace
lf00 = tk.LabelFrame(f, text='Replace this: Quick brown fox jumped.')
lf00.grid(row=0, column=0, padx=(20, 2), pady=20, sticky='e')

l_from = tk.Label(lf00,text='From');l_from.grid(row=0,column=0)
l_to = tk.Label(lf00,text='To');l_to.grid(row=0,column=1)

e_from = tk.Entry(lf00);e_to = tk.Entry(lf00)

b20 = tk.Button(lf00,text='RegexReplace',
                command= lambda x=[e_from,e_to]: find_and_replace(x[0],x[1]))

b21 = tk.Button(lf00,text='MultiReplace',
             command= lambda x=[e_from,e_to]: find_and_replace(x[0],x[1]))

>Solution :

Bind to the appropriate widget

e_from = tk.Entry(lf00);e_to = tk.Entry(lf00)
# add '_event' param to the lambda to absorb the unused event
e_from.bind("<Return>",  lambda _event, x=[e_from,e_to]: find_and_replace(x[0],x[1]) )

Leave a Reply