문제

I'm making a tkinter python program and I want to use a try/except command so the program won't malfunction when a user type in a letter or other non-numeric sign.

Here's the code:

def count(): 
    fahrenheit = float(inputEntry.get()) 
    celsius = (fahrenheit - 32) * 5 / 9 
    if celsius > 0: # Metod för hanteringen av bakgrundsfärger och värden.
        infoLabel.configure(bg='#980000', text='Det blir %.2f grader Celsius.' % (celsius,))
    elif celsius  < 0:
        infoLabel.configure(bg='#3366CC', text='Det blir %.2f grader Celsius.' % (celsius,))
    else:
        infoLabel.configure(bg='#00CC33', text='Det blir %.2f grader Celsius.' % (celsius,))

I've tried solving the problem by this:

def count():  
    fahrenheit = float(inputEntry.get())
    celsius = (fahrenheit - 32) * 5 / 9
try:
    if celsius > 0:
        infoLabel.configure(bg='#980000', text='Det blir %.2f grader Celsius.' % (celsius,))
    elif celsius  < 0:
        infoLabel.configure(bg='#3366CC', text='Det blir %.2f grader Celsius.' % (celsius,))
    else:
        infoLabel.configure(bg='#00CC33', text='Det blir %.2f grader Celsius.' % (celsius,))
except ValueError:
        infoLabel.configure(bg='#00CC33', text='You must type the value in digits!')

When I run the code and enter "sdf" in the number box, I get this error message:

ValueError: could not convert string to float: sdf

Any solutions?

I want the message in the GUI to say "You must type the value in digits!" when I type in a letter.

(Full code listed below)

#- coding: UTF-8 -*-

"""
Python v2.7 Mac OSX10.9
"""

import Tkinter
import tkMessageBox

main_window = Tkinter.Tk() # vad hela rutan/framen skall heta
top_frame = Tkinter.Frame(main_window) #i parantes, skriver var framen ska vara
bottom_frame = Tkinter.Frame(main_window) #i parantes, dvs bottom_frame ska va inne i main_window
inputLabel = Tkinter.Label(bottom_frame, text='Skriv antal grader =>', font=('helvetica', 14))
inputEntry = Tkinter.Entry(bottom_frame, width = 5, bg='white', font=('helvetica', 14))
infoLabel = Tkinter.Label(top_frame, height = 5, width=40, text='Välkommen till Temperaturomvandlaren!\n' \
                                                            'Nedan kan du omvandla \nFahrenheit till Celsius.', font=('helvetica', 14), bg='white', fg='#180000')

def main():
    setupWindow() # 
    Tkinter.mainloop()

def setupWindow():
    main_window.geometry('320x170+500+250') # storleken på fönstret, samt 500+250 anger var fönstret ska va när det öppnas
    main_window.title('Temperaturkonverteraren')

    Convert = Tkinter.Button(bottom_frame, text = "Konvertera", command = count) # Knappen Konvertera kallar på count
    Reset = Tkinter.Button(bottom_frame, text = 'Börja om', command = restart) # Börja om-knappen kallar på restart
    infoLabel.pack()
    top_frame.pack()
    bottom_frame.pack()
    inputEntry.pack()
    Convert.pack()
    Reset.pack()


def count():
    fahrenheit = float(inputEntry.get()) 
    celsius = (fahrenheit - 32) * 5 / 9 
    try:
        if celsius > 0: 
            infoLabel.configure(bg='#980000', text='Det blir %.2f grader Celsius.' % (celsius,))
        elif celsius  < 0:
            infoLabel.configure(bg='#3366CC', text='Det blir %.2f grader Celsius.' % (celsius,))
        else:
            infoLabel.configure(bg='#00CC33', text='Det blir %.2f grader Celsius.' % (celsius,))
    except ValueError:
        infoLabel.configure(bg='#00CC33', text='Du måste ange värde i siffra.')

def restart(): 
    infoLabel.configure(bg='white', fg='#180000', text='Välkommen till Temperaturomvandlaren!\n' \
                                                            'Nedan kan du omvandla \nFahrenheit till Celsius.', font=('helvetica', 14))
    inputEntry.delete(0, len(fahrenheit.get()))                                                        


if __name__ == '__main__': 
    main() 
도움이 되었습니까?

해결책

It is the float() call that raises ValueError, so use a try statement to protect that:

try:
    fahrenheit = float(inputEntry.get())
except ValueError:
    infoLabel.configure(bg='#00CC33', text='You must type the value in digits!')
else:
    celsius = (fahrenheit - 32) * 5 / 9
    color = '#980000' if celcius > 0 else '#3366CC' if celcius < 0 else '#00CC33'
    infoLabel.configure(bg=color, text='Det blir %.2f grader Celsius.' % (celsius,))
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top