Reputation: 31
I'm having trouble with an IF statement resulting from when a button is clicked. The code I have so far is below, basically what I need is once the button is pressed it asks the question 'Are you sure you want to update?' This works fine. The user then clicks yes or no. No closes the pop up box (working ok), if the user clicks yes then it checks to see if the entry is blank. If it is it keeps the original variable (working ok), it also checks to see if the entry is a float and if it isn't then return an error message, this brings back an error message even if it is a float, what I want it to do is if its a float then use the entered value which the else statement should do. but it keeps bringing back the messagebox error.
def updatetimings():
ask = messagebox.askquestion('Validation','Are you sure you want to update timings?')
if ask =='yes':
try:
a = newv5c.get()
if a == "":
e1 = v5c_timing
elif type(a) != float :
messagebox.showinfo('Error','Please enter decimal numbers only')
else:
e1 = a
except ValueError:
messagebox.showinfo('Error','Please enter decimal numbers only')
pass
Maybe Psuedocode may help:
BUTTON CLICKED:
QUESTION ASKED NO CLOSES WINDOW YES = IF ENTRY IS BLANK THEN USE OLD VARIABLE OR ENTRY = FLOAT THEN USE NEW VARIABLE IF ITS ANY OTHER TYPE THEN SHOW ERROR MESSAGEBOX ,'WRONG TYPE'
I've set the entry as a StringVar() if that is the problem.
Thanks
Upvotes: 0
Views: 51
Reputation: 53
In their comment, hiro protagonist suggested that a
might always be a str
. I agree that this is probably the case (although I don't know for sure). This is one way to structure your code to use float()
to parse a value out of a
:
def updatetimings():
ask = messagebox.askquestion('Validation','Are you sure you want to update timings?')
if ask == 'yes':
a = newv5c.get()
if a == '':
e1 = v5c_timing
else:
try:
# Try parsing a as a float. If it works, store the result in e1.
e1 = float(a)
except ValueError:
# If we're not able to parse a as a float, then show an error message.
messagebox.showinfo('Error','Please enter decimal numbers only')
I hope this helps!
Upvotes: 2