1

In my Tkinter application I have an Entry widget and the user should fill it with numbers.

Is it possible to restrict the entered values to int, float and long?

Specifically, the user should only input a number:

  • This can be float, int, long.
  • The user can only put one . (a number doesn't have 2 dot anyway).

import tkinter as tk

class App():
    def __init__(self):
        self.root = tk.Tk()
        vcmd = (self.root.register(self.on_validate), '%d', '%i', '%s', '%S')
        self.entry = tk.Entry(self.root, validate="key", validatecommand=vcmd)
        self.entry.pack()
        self.root.mainloop()

    def on_validate(self, d, i, s, S,):
        if S == "-" and s.count('-') != 1 and int(i) == 0:
            return True
        if d == "0":
            return True
        try:
            return int(S) >= 0 and int(S) <= 9
        except:
            if S == "." and s.count('.') != 1:
                return True
            return False

app = App()
Cœur
  • 37,241
  • 25
  • 195
  • 267
user1586263
  • 61
  • 1
  • 3
  • 1
    possible duplicate of [Python/Tkinter: Interactively validating Entry widget content](http://stackoverflow.com/questions/4140437/python-tkinter-interactively-validating-entry-widget-content) – Bryan Oakley Aug 09 '12 at 02:08

1 Answers1

1

You cannot restrict the datatype, but you can restrict the characters that are allowed. See the answer to the question Python/Tkinter: Interactively validating Entry widget content

Community
  • 1
  • 1
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685