Home > OS >  Only allow floats in entry box
Only allow floats in entry box

Time:10-02

I have an entry box where I would like the user to only be able to enter floats.

Here is my function so far:

class Prox(Entry):
    '''Entry widget that only accepts digits'''
    def __init__(self, master=None, **kwargs):
        self.var = StringVar(master)
        self.var.trace('w', self.validate)
        Entry.__init__(self, master, textvariable=self.var, **kwargs)
        self.get, self.set = self.var.get, self.var.set
    def validate(self, *args):
        value = self.get()
        if not value.isdigit():
            self.set(''.join(x for x in value if x.isdigit()))

It works great for integers but doesn't allow the user to enter a float. I saw a few solutions that returns an error when the user doesn't enter a float like:

try:
    value=float(input(“Enter your value”))

except:
    print(“Error. Non numeric values not allowed”)

But that is not really what I am trying to do. I would like the user not to be able to enter anything else than a float (like what I have so far with integers)

CodePudding user response:

Use validate command as indicated by Bryan. Make use try-except block to check if the value is a valid number.

minimal example

import tkinter as tk

def check_float(val):

    try:
        float(val)
        cvt = True
    
    except ValueError:
        cvt = False

    return cvt or val==""

root = tk.Tk()

reg = root.register(check_float)
entry = tk.Entry(root, validate="key", validatecommand=(reg, '%P'))
entry.pack()

root.mainloop()

CodePudding user response:

Alright I think I found an answer:

class Prox(Entry):
    '''Entry widget that only accepts digits'''
    def __init__(self, master=None, **kwargs):
        self.var = StringVar(master)
        self.var.trace('w', self.validate)
        Entry.__init__(self, master, textvariable=self.var, **kwargs)
        self.get, self.set = self.var.get, self.var.set
    def validate(self, *args):
        value = self.get()
        dotCounter = []
        if not value.isdigit() or value != '.':
            self.set(''.join(x for x in value if x.isdigit() or x=='.'))
            for i in value:
                if i == '.':
                    dotCounter.append(i)
                    if len(dotCounter) > 1:
                        self.delete(len(self.get())-1)
                        dotCounter.clear()

The function allows to enter only numbers and commas and checks if the user enters more than one comma. If he does it automatically removes it.

Maybe not the cleanest way to go about it but it works....

  • Related