Detect the moment entered in an Entry


I'm doing a program that consists of a single Entry ().

The thing is that I want you to immediately detect what is written and act one way or another. So when you finish putting the last character of for example "add", do one thing.

I've tried it with the .get () function in a if but there's no way.

Here goes the code:

general.set("Pon ayuda para poder ayudarte")

locale.setlocale(locale.LC_ALL,"es-ES") #Establecemos región como "España"

dt = #Sacamos la hora y la fecha del sistema
fecha = dt.strftime("%x") #Establecemos la variable 'fecha' y 'hora' como la 
fecha y la hora actual
hora = dt.strftime("%X")

frame = Frame(root,width=360,height=400,bg="powder blue")

entryg = Entry(frame,textvariable=general,bg="powderblue",font= ("",24),justify="center"),y=0)

if general == "añadir":
    print("si") #Print de comprobación(No funciona)

asked by Esteban 06.08.2018 в 18:17

1 answer


If you want the check to be done automatically, that is, at the same time that the user finishes entering the last character of a given chain in the Entry , a certain action is performed, without the need for the user indicates that he has stopped writing, the solution is to use the method trace_add of the StringVar associated with Entry so that a callback is called every time the text is modified by the user:

from functools import partial
import tkinter as tk

root = tk.Tk()
root.resizable(1, 1)
frame = tk.Frame(root, width=360, height=400, bg="powder blue")
frame.pack(fill="both", expand=1)

general = tk.StringVar()
entryg = tk.Entry(frame, textvariable=general, bg="powderblue",
                  font=("",24), justify="center"
                  ), y=0)

def on_text(*args):
    text = entryg.get().lower()
    if text == "añadir":
    elif text == "ayuda":

general.trace_add("write", on_text)


Logically you should be careful in choosing the "key" words to avoid conflicts between them, for example:


view ificar


Important: The trace_add method was added in Python 3.6 a> to replace trace and trace_variable . In case of using an older version, trace should be used.

If instead you want the check to be done only when the user presses ENTER on Entry (or any other key) you must use the bind method of Entry to associate the event to the callback. in the previous example it would only change:

general.trace_add("write", on_text)


entryg.bind("<Return>", on_text)

Another possibility would be to use the validation system that includes the Entry using the option validatecommand , which allows us to launch a callback (thought to validate the content of Entry ) before an event that indicates the end of the writing (pressed of a key and loss / gain of the focus basically )

answered by 06.08.2018 / 19:29