实现效果
程序代码
import re
import tkinter
import tkinter.messagebox
root = tkinter.Tk()
root.geometry('300x270+400+100')
root.resizable(False,False)
root.title('简易计算器')
contnetVar = tkinter.StringVar(root , '')
contnetEntry = tkinter.Entry(root, textvariable=contnetVar)
contnetEntry['state'] = 'readonly'
contnetEntry.place(x=10,y=10,width=280,height=20)
def buttonClick(btn):
contnet = contnetVar.get()
if contnet.startswith('.'):
contnet = '0'+contnet
if btn in '0123456789':
contnet += btn
elif btn =='.':
lastPart = re.split(r'\+|-|\*|/]',contnet)[-1]
if '.' in lastPart:
tkinter.messagebox.showerror('错误','小数点太多了')
return
else:
contnet += btn
elif btn == 'C':
contnet =''
elif btn == '=':
try:
contnet = str(eval(contnet))
except:
tkinter.messagebox('错误','表达式错误')
return
elif btn in operators:
if contnet.endswith(operators):
tkinter.messagebox.showerror('错误','不允许存在连续运算符')
return
contnet += btn
elif btn == 'Sqrt':
n = contnet.split('.')
if all(map(lambda x:x.isdigit(),n)):
contnet = eval(contnet)**0.5
else:
tkinter.messagebox.showerror('错误','表达式错误')
return
contnetVar.set(contnet)
btnClear = tkinter.Button(root,text='清空',command=lambda :buttonClick('C'))
btnClear.place(x=40,y=40,width=80,height=20)
btnClear = tkinter.Button(root,text='=',command=lambda :buttonClick('='))
btnClear.place(x=170,y=40,width=80,height=20)
digits = list('0123456789.')+['Sqrt']
index = 0
for row in range(4):
for col in range(3):
d = digits[index]
index += 1
btnDigit = tkinter.Button(root, text=d, command=lambda x=d : buttonClick(x))
btnDigit.place(x=20+col*70, y=80+row*50, width=50, height=20)
operators = ('+','-','*','/','**','//')
for index, operator in enumerate(operators):
btnOperator = tkinter.Button(root, text=operator, command=lambda x=operator : buttonClick(x))
btnOperator.place(x=230, y=80 + index * 30, width=50, height=20)
root.mainloop()