功能完善
- 除法除数为0的异常处理
- 非数字输入的异常处理
代码实现
from tkinter import *
from tkinter.messagebox import showinfo
class Calculator(Frame):
def keyPress(self,display):
text_check = list(display.get())
for i in range(len(text_check)):
if not(text_check[i] in list(''.join('0123456789+-*/'))):
display.set('')
#or use 'raise SystemError("please input number or operator!")'
showinfo(title='warning', message='please input number or operator!')
elif('/0' in display.get()):
display.set('')
showinfo(title='warning', message='division by zero, please input number and operator again!')
else:
pass
def __init__(self):
Frame.__init__(self)
self.pack(expand=YES, fill=BOTH)
self.master.title('calculator')
self.master.rowconfigure( 0, weight = 1 )
self.master.columnconfigure( 0, weight = 1 )
self.grid( sticky = W+E+N+S )
display = StringVar()
#add entry ,use grid method
#textvariable must use 'display' instead of 'StrinvVar()', or click button shows nothing in Entry
entry = Entry(self, relief=SUNKEN, textvariable=display)
#W+E+N+S means that the widget should be expanded in both directions. Default is to center the widget in the cell.
entry.grid(row=0, column=0, columnspan=4, sticky=W+E+N+S)
entry.bind('<KeyRelease>', lambda s=self, w=display:self.keyPress(w))
#add button, use grid method
grid = '789+456-123*0./='
for index,textChar in enumerate(grid):
a = Button(self, text=textChar, width=5, command=lambda text=textChar:display.set(display.get() + text))
a.grid(row=1+index//4, column=index%4)
button_text = a.cget("text")
#print(button_text)
if button_text == '=':
a.config(command=lambda:display.set(eval(display.get())))
#add clear button
b = Button(self, text="clear", width=20, command=lambda:display.set(""))
b.grid(row=7, column=0, columnspan=4, sticky=W+E+N+S)
if __name__ == '__main__':
Calculator().mainloop()
实现结果
输入字母a:
除数为0:
参考资料
Restricting the value in Tkinter Entry widget
How to insert only some specified characters in a tkinter Entry widget
TypeError: ‘type’ object is not subscriptable when indexing in to a dictionary