0

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

1
  • a is probably always a str; if you want to know if that string can represent a float you need to (try to) cast it with float(a). Commented Apr 29, 2017 at 9:17

1 Answer 1

2

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.