Home > Software engineering >  bind enter key to run a command in tkinter label
bind enter key to run a command in tkinter label

Time:11-09

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".

Wanted 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

MWE

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)
e_from.grid(row=1,column=0);e_to.grid(row=1,column=1)

b20 = tk.Button(lf00,text='RegexReplace',
                command= lambda x=[e_from,e_to]: find_and_replace(x[0],x[1]))
b20.grid(row=2,column=0,sticky='w')

b21 = tk.Button(lf00,text='MultiReplace',
             command= lambda x=[e_from,e_to]: find_and_replace(x[0],x[1]))
b21.grid(row=2,column=1,sticky='e')
win.mainloop()

CodePudding user response:

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