1

As stated in the title, I'm trying to delete a character right after it was entered into a text field.

import tkinter as tk

window = tk.Tk()
input = tk.Text()
input.pack()


def handle_keypress(event):
  print("test")
  input.delete("1.0")

input.bind("<Key>", handle_keypress)

window.mainloop()

The following code deletes the character only after another one is typed. The print statement, however, works instanly as expected. I wonder what is causing this behaviour and how it can be fixed. Thankful for any clue.

mykhailohoy
  • 442
  • 4
  • 15
  • 1
    If you return `"break"` from a `""` event, the key isn't going to be processed by the text widget. So replace the `input.delete("1.0")` with `return "break"`. – TheLizzard May 03 '21 at 20:06
  • 1
    The key binding gets executed *before* the Text actually inserts the character - this allows you to modify the character that gets inserted, or prevent the insertion altogether. – jasonharper May 03 '21 at 20:06
  • If you don't want any key to be input into the text box, wht don't you just disable it? – acw1668 May 04 '21 at 00:31

1 Answers1

0

Here is the code you've provided, I changed the Tk.text to a tk.entry, you can still resize through .configure, its essentially the same thing.

If the problem you are trying to resolve is removing a character before it is visible you need to use '''tk.END''' to essentially clear the entry as a key is pressed, if you run the code nothing will show but you'll still print the character that you pressed.

I've also changed the bind to the actual window instead of the entry, but it should work the same either way

If you have any questions let me know

import tkinter as tk

window = tk.Tk()

def handle_keypress(event):
    #capture character entered, print it, then empty the textfield
    print(event.char)
    input1.delete(0, tk.END)

#changed from tk.text to tk.entry, you can use .configure(textvariable) to have further control
input1 = tk.Entry()
input1.pack()

#binded to window    
window.bind("<Key>", handle_keypress)
window.mainloop()