python - Python 中的华氏度转换器,使用 try/except 命令排除字母

标签 python try-catch except converters

我正在制作一个 tkinter python 程序,我想使用 try/except 命令,这样当用户输入字母或其他非数字符号时程序就不会出现故障。

代码如下:

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,))

我尝试通过以下方式解决问题:

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!')

当我运行代码并在数字框中输入“sdf”时,我收到以下错误消息:

ValueError: could not convert string to float: sdf

有什么解决办法吗?

我希望 GUI 中的消息显示“您必须输入数字值!”当我输入一封信时。

(下面列出了完整代码)

#- 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() 

最佳答案

正是 float() 调用引发了 ValueError,因此请使用 try 语句来保护 :

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,))

关于python - Python 中的华氏度转换器,使用 try/except 命令排除字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20954034/

相关文章:

Python For i in range(len(str)) : last iteration prints None

sql - Sybase 中的错误处理

python - try 语句中的“除了”(在 while 循环内)不起作用

Python - 总结 try-except 语句

Python Bokeh : How to update a Toggle button - defined in the main - in a subroutine

python - 当键乱序时比较字典列表

c# - TRY block 中的异常会中断它的执行吗?

python - Try except block 用于多个验证错误

python - 如何检查 tkinter 中的条目是否有一个或多个零

c# - 哪种布局 if() { try {} catch {} } 更好?