How to capture each key pressed in an entry with Tkinter?

Asked

Viewed 104 times

2

Using the library Tkinter, i would like to perform a database search with each key pressed by the user in an entry, so that the result is automatically shown in a Listbox as I type. How can I do it ?

1 answer

1

You just need to create an event using Entry.bind() called "<Any-KeyPress>" passing the function you want to call. That way, whenever the user presses any key, having Entry focus, the function will be called. See this example I created below:

from tkinter import *

def checkDatabase(event = None):
    root.after(100, lambda: print("Procurando por", entry.get()))

root = Tk()
Label(root, text = "Digite abaixo o que procura").pack()

entry = Entry(root)
entry.bind("<Any-KeyPress>", checkDatabase)
entry.pack()

root.mainloop()

One very interesting thing that we can observe in this example above, is that within the function checkDatabase, I am using the method after(). I used this method, so that the function is not executed before the character is inserted in Entry, since the event is detected before.

  • ah ta so I can put in this function to search what I want in the database in real time , I understood thank I will try to do

Browser other questions tagged

You are not signed in. Login or sign up in order to post.