Home > Enterprise >  How to bind keypresses in a tkinter entry widget to process the entered characters instead of enteri
How to bind keypresses in a tkinter entry widget to process the entered characters instead of enteri

Time:10-24

I am required to handle keypad "-", " " and also "Escape" and "Return" key presses in a method. I've written a global handler so the key press does not have to be bound to any particular widget.

import tkinter as tk

class Controller:
    def __init__(self):
        self.model = Model()
        self.view = View(self)
        self._bind_keys()
        self.view.root.mainloop()

    def _bind_keys(self):
        self.view.root.bind('<Escape>', self._global_key_handler)
        self.view.root.bind('<Return>', self._global_key_handler)
        self.view.root.bind('-', self._global_key_handler)
        self.view.root.bind(' ', self._global_key_handler)

    def _global_key_handler(self, event: tk.Event):
        if event.keysym == 'Escape':
            self._reset_all_fields()
        if event.keysym == 'Return':
            self.calculate_values()
        if event.char == '-':
            self._reset_all_fields()
        if event.char == ' ':
            self.copy_fields_to_table()

As long as the windows has no entry widget focused there is no problem. But if there is a entry focused, " " and "-" characters are written to the field.

I was thinking about binding the entry widgets to another handler. Something like:

def _entry_key_handler(event):
    if event.char == '-':
        print('reset')
        return
    if event.char == ' ':
        print(' ')
        return
    event.widget.insert(tk.END, event.char)

The idea was to handle " " and "-" but write everything else to the entry with the last line in the code block. I just can't find a way to supress the original behaviour of the keypress event.

Is there a way to prevent a regular keypress to write into the entry field?

I'm using Python 3.10

CodePudding user response:

Is there a way to prevent a regular keypress to write into the entry field?

You can create bindings for these keys directly on the entry widget, and have the function return the string "break". That will prevent the default bindings from functioning.

For a more comprehensive explanation of how key bindings work, see this answer to the question Basic query regarding bindtags in tkinter

  • Related