有没有办法让python检测字母字符并生成错误消息?

2024-05-18 10:08:16 发布

您现在位置:Python中文网/ 问答频道 /正文

这里是tkinter/python新手。我使用tkinter构建了一个计算器,但我似乎找不到任何方法允许python检测输入到entry小部件中的字母字符。我的目标是让它检测字母字符并显示错误消息

这是我的密码:

from tkinter import *
root = Tk()
#Title of the Window(s)
root.title("Jeff's Geometry Calculator")

#Fonts for this project
LARGEFONT = ("Verdana", 35)
BUTTONFONT = ("Times", 15)
ANSWERFONT = ("Courier", 25, "bold")
ANSWERLABELFONT = ("Courier", 25)
DESCRIPTIONFONT = ("Verdana", 18)
DESCRIPTIONFONT1 = ("Verdana", 12)

descriptionLabel = Label(root, text="Cube Volume Calculator", font=LARGEFONT, padx=50, pady=50)
descriptionLabel.grid(row=0, column=0)

equationLabel = Label(root, text="Cube Volume Equation: l³", font=DESCRIPTIONFONT)
equationLabel.grid(row=1, column=0)

equationLabel1 = Label(root, text="Note: l = length", font=DESCRIPTIONFONT1)
equationLabel1.grid(row=2, column=0)

numEntry = Entry(root, width=10)
numEntry.grid(row=3, column=0)

def cubeVolumeAnswer():
  cubeNum = (numEntry.get())
  result = float(cubeNum) * float(cubeNum) * float(cubeNum)
  answerLabel.config(text=str(result))

myButton = Button(root, text="Calculate", font=BUTTONFONT, command=cubeVolumeAnswer, padx=50, pady=50)
myButton.grid(row=4, column=0)

number = str(numEntry.get())

answerLabel = Label(root, text="", font=ANSWERFONT)
answerLabel.grid(row=6, column=0)

answerLabel1 = Label(root, text="Answer: ", font=ANSWERLABELFONT)
answerLabel1.grid(row=5, column=0)


root.mainloop()

提前谢谢


Tags: texttkinter字母columnrootfloat字符label
1条回答
网友
1楼 · 发布于 2024-05-18 10:08:16

您可以使用try/except语句,基本上,try将尝试执行任务,但如果出现错误,它将执行except块,而不是控制台中的恐吓性错误消息:

try:
    print(1 + z)
except:
    print("invalid equation")

在您的情况下,您可以简单地:

def cubeVolumeAnswer():
    cubeNum = (numEntry.get())
    try:
        result = float(cubeNum) * float(cubeNum) * float(cubeNum)
    except:
        result = "invalid equation"
    answerLabel.config(text=str(result))

相关问题 更多 >