0

I've been trying to implement validation in to an entryfield in tkinter so you can only enter integers: this is the code I have right now:

import tkinter as tk

class window2:
  def __init__(self, master):
    self.panel2 = tk.Frame(master)
    self.panel2.grid()
    self.button2 = tk.Button(self.panel2, text = "Quit", command = self.panel2.quit)
    self.button2.grid()

    self.entryfields()

def entryfields(self):

    vcmd = (self.register(self.validate),
            '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
    self.text1 = tk.Entry(self.panel2, validate = 'key', validatecommand = vcmd)
    self.text1.grid()
    self.text1.focus()

def validate(self, action, index, value_if_allowed,
    prior_value, text, validation_type, trigger_type, widget_name):
    if(action=='1'):
        if text in '0123456789.-+':
            try:
                float(value_if_allowed)
                return True
            except ValueError:
                return False
        else:
            return False
    else:
        return True

if __name__ == "__main__":

root1 = tk.Tk()
window2(root1)
root1.mainloop()

Some of the code was taken from this forum as well. I think it's an inheritance issue which I'm missing out on.

Cœur
  • 37,241
  • 25
  • 195
  • 267
ashkl
  • 47
  • 1
  • 9
  • You say you want to limit input to integers but your code tries converting it to a float. Which do you care about, integers or floats? If just integers, can the value have a sign? – Bryan Oakley Feb 19 '17 at 21:23
  • Sorry for the confusion, i only want the user to type in floats only. – ashkl Feb 19 '17 at 21:40

1 Answers1

1

To do validation for floats, all you need is for the validation command to be given the value if the edit is allowed (%P). Try to convert that to a float, and return False if it fails and True if it succeeds.

For example:

class window2:
    ...    
    def entryfields(self):
        vcmd = (self.panel2.register(self.validate), '%P')
        self.text1 = tk.Entry(self.panel2, validate = 'key', validatecommand = vcmd)
        self.text1.grid()
        self.text1.focus()

    def validate(self, value_if_allowed):
        if value_if_allowed == "":
            # allow null entries so the user can delete everything
            # before entering a value if they wish. 
            return True

        try:
            float(value_if_allowed)
            return True

        except ValueError:
            self.panel2.bell()
            return False

For more information about entry widget validation, see this answer: https://stackoverflow.com/a/4140988/7432

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