Una forma es validar el input del usuario y solo permitir el ingreso si el resultado es lo que esperamos. Esta sería una prueba de concepto:
import tkinter as tk
class window:
def __init__(self, master):
self.panel = tk.Frame(master)
self.panel.grid()
self.button = tk.Button(self.panel, text = "Salir", command = self.panel.quit)
self.button.grid()
"""
'%d' Action code: 0 for an attempted deletion, 1 for an attempted insertion, or -1 if the callback was called for focus in, focus out, or a change to the textvariable.
'%i' When the user attempts to insert or delete text, this argument will be the index of the beginning of the insertion or deletion. If the callback was due to focus in, focus out, or a change to the textvariable, the argument will be -1.
'%P' The value that the text will have if the change is allowed.
'%s' The text in the entry before the change.
'%S' If the call was due to an insertion or deletion, this argument will be the text being inserted or deleted.
'%v' The current value of the widget's validate option.
'%V' The reason for this callback: one of 'focusin', 'focusout', 'key', or 'forced' if the textvariable was changed.
'%W' The name of the widget.
"""
vcmd = (master.register(self.validate),
'%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
self.text = tk.Entry(self.panel, validate = 'key', validatecommand = vcmd)
self.text.grid()
self.text.focus()
def validate(self, action, index, value_if_allowed,
prior_value, text, validation_type, trigger_type, widget_name):
if len(value_if_allowed)==0:
return True
if text in '0123456789.-+':
try:
float(value_if_allowed)
return True
except ValueError:
return False
else:
return False
root = tk.Tk()
window(root)
root.mainloop()
Hemos creado una función de validación validate
que se evalúa con cada tecla ingresada, lo que hace es solo permitir el ingreso si:
- El resultado final será una cadena en blanco
- Es uno de los caracteres válidos
- El resultado final es convertible a un float
Fuente: https://stackoverflow.com/questions/8959815/restricting-the-value-in-tkinter-entry-widget