0

If i want an entry box in Tkinter that only accepts floating point numbers that are greater than or equal to 0.0 and less than or equal to 1.0 how would i do that?

  • 1
    You mean that it should check whether the input that you have given is acceptable after collecting it or you want him to check while typing? – Stijn Van Daele Mar 26 '17 at 15:25
  • Add a callback function to entry box(key up and keydown), every key down `save value to a variable`, every key up `check value if not valid restore old value`. Mean rising/falling edge operations. – dsgdfg Mar 26 '17 at 15:27

2 Answers2

1

The proper way it to use tkinter's validate capabilities. But it's really a PIA to use.

dsgdfg has a good answer, but I can make that a lot neater, robust, and more dynamic:

import Tkinter as tk

class LimitedFloatEntry(tk.Entry):
    '''A new type of Entry widget that allows you to set limits on the entry'''
    def __init__(self, master=None, **kwargs):
        self.var = tk.StringVar(master, 0)
        self.var.trace('w', self.validate)
        self.get = self.var.get
        self.from_  = kwargs.pop('from_', 0)
        self.to = kwargs.pop('to', 1)
        self.old_value = 0
        tk.Entry.__init__(self, master, textvariable=self.var, **kwargs)

    def validate(self, *args):
        try:
            value = self.get()
            # special case allows for an empty entry box
            if value not in ('', '-') and not self.from_ <= float(value) <= self.to:
                raise ValueError
            self.old_value = value
        except ValueError:
            self.set(self.old_value)

    def set(self, value):
        self.delete(0, tk.END)
        self.insert(0, str(value))

You use it just like an Entry widget, except now you have 'from_' and 'to' arguments to set the allowable range:

root = tk.Tk()
e1 = LimitedFloatEntry(root, from_=-2, to=5)
e1.pack()
root.mainloop()
Community
  • 1
  • 1
Novel
  • 13,406
  • 2
  • 25
  • 41
0

If you want to call a button to check whether, this is a way to do it.

from tkinter import *

class GUI():
    def __init__(self, root):

        self.Entry_i = Entry(root, bd = 5)

        self.test = StringVar()
        Label_i = Label(root, textvariable = self.test)
        Button_i = Button(root, text = "Go", command = self.floatornot)

        self.Entry_i.grid()
        Label_i.grid()
        Button_i.grid()
        mainloop()

    def floatornot(self):

        test = self.Entry_i.get()
        if float(test) < 0 or float(test) > 1:
            self.test.set("Good")
        else: 
            self.test.set("")

root = Tk()
GUI(root)

The button will call the floatornot function. This will get the value of the entry and check if it okay or not. Depending on the result the value of the label will be changed.

Stijn Van Daele
  • 285
  • 1
  • 14