我在python中构建了一个计算器并且它可以工作,除非有人尝试将数字除以零,否则它们不会收到“无效的语法!”计算器输入错误。我怎么能这样做消息“无效的语法!”显示在计算器输入?
from tkinter import *
class calc:
def getandreplace(self):
self.expression = self.e.get()
self.newtext=self.expression.replace(self.div,'/')
self.newtext=self.newtext.replace('x','*')
def equals(self):
self.getandreplace()
try:
self.value= eval(self.newtext)
except SyntaxError or NameError:
self.e.delete(0,END)
self.e.insert(0,'Invalid Syntax!')
else:
self.e.delete(0,END)
self.e.insert(0,self.value)
def clearall(self):
self.e.delete(0,END)
def action(self,argi):
self.e.insert(END,argi)
def __init__(self,master):
self.e = Entry(master)
self.e.grid(row=0,column=0,columnspan=2)
self.e.focus_set()
self.div='/'
Button(master,text="=",width=4, command=lambda:self.equals()).grid(row=4, column=1)
Button(master,text='AC',width=4, command=lambda:self.clearall()).grid(row=2, column=0)
Button(master,text="/",width=4, command=lambda:self.action(self.div)).grid(row=1, column=1)
Button(master,text="5",width=4,command=lambda:self.action(5)).grid(row=2, column=1)
Button(master,text="0",width=4,command=lambda:self.action(0)).grid(row=4, column=0)
root = Tk()
obj=calc(root)
root.mainloop()
我尝试过except NameError or SyntaxError or ZeroDivisionError
,但它不起作用。该错误仅出现在shell中,而不是“无效的语法!”。
答案 0 :(得分:1)
将ZeroDivisionError
添加到您的例外列表中:
except (SyntaxError, NameError, ZeroDivisionError):