Reputation: 789
Im sitting in a situation i can't figure out myself.
When im using the Entry widget to get user interaction i am having a hard time finding the right way to validate the data.
The situation:
I have two Entry widgets in which the user must enter two variables which has to be floats.
While i can run a program that only works properly if the entered value is a float, if i then leave it blank or enter a letter shuts down - therefor i want to validate the entry to be a float:
variableentry = Entry(root and so on)
variableentry.grid()
I am using the:
variablename = float(variableentry.get())
And when i:
print(type(variablename)
i get the message:
<class 'float'>
thus i am unable to use the
#...
try:
if(variablename is not float):
messagebox.showerror("Error", "Incorrect parameter")
return
This obviously isnt working since the variablename is of class 'float' and not float, i have tried different ways of entering instead of float in the if statement - without any luck.
Any ideas?
In advance, thanks!
Best regards,
Casper
EDIT:
I have found the:
from Tkinter import *
class ValidatingEntry(Entry):
# base class for validating entry widgets
def __init__(self, master, value="", **kw):
apply(Entry.__init__, (self, master), kw)
self.__value = value
self.__variable = StringVar()
self.__variable.set(value)
self.__variable.trace("w", self.__callback)
self.config(textvariable=self.__variable)
def __callback(self, *dummy):
value = self.__variable.get()
newvalue = self.validate(value)
if newvalue is None:
self.__variable.set(self.__value)
elif newvalue != value:
self.__value = newvalue
self.__variable.set(self.newvalue)
else:
self.__value = value
def validate(self, value):
# override: return value, new value, or None if invalid
return value
from http://effbot.org/zone/tkinter-entry-validate.htm
However the rest of the code is not written in classes (i know this is not optimal but it is demanded by the teacher) will that effect the above example? And how would i make it fit my needs?
Upvotes: 0
Views: 3473
Reputation: 8550
What you want to do is to try converting the contents of the entry box to a float, and report an error message if the conversion is not possible. Doing variablename = float(variableentry.get())
is fine, but to catch errors raised by float
if the string it is given cannot be converted, you must wrap the line in a try block, and catch the ValueError raised by float
. If there is no exception, you can proceed with the code:
try:
variablename = float(variableentry.get())
except ValueError:
# error messagebox, etc
else:
# do stuff with variablename
Upvotes: 2