I want to restrict users to enter digits only in an Entry widget.
I have been able to capture the key after it has been entered and displayed as well as extract what is already in the Entry widget; but I have not found a way of preventing the key from being added to the entry box.
The manipulation I am able to do on self.entry.get(), appears to be restricted to being prior to event.char being added, rather than after.
For example, entering "12b" in the code below, I get "1b"; but what I want is "12".
I tried to change the value of event.char=""; but that did not work.
Any help will be appreciated.
# generic python libraries
import tkinter as tk
from tkinter import ttk, END
class MyWindow(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.entry = ttk.Entry(self)
self.entry.grid(row=0, column=0, padx=5, pady=5)
self.entry.bind('<Key>', self.handle_entry_key_press)
def handle_entry_key_press(self, event) -> None:
if not event.char.isdigit():
print(self.entry.get(), event.char)
self.entry.delete(self.entry.index(END)-1)
if __name__ == "__main__":
root = tk.Tk()
MyWindow(root).grid()
root.mainloop()
CodePudding user response:
You can use the following:
class MyWindow(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
sv = StringVar()
sv.trace_add("write", lambda _a,_b,_c, sv = sv: self.delete_last_char(sv))
self.entry = ttk.Entry(self, textvariable = sv)
self.entry.grid(row=0, column=0, padx=5, pady=5)
def delete_last_char(self, var):
print(var.get())
var.set("".join([c for c in self.entry.get() if c.isdigit()]))
Instead of catching key events, it checks variable each time it changes and removes any non-digit characters.