python-计算器优化版

import struct
from tkinter import *
from tkinter import messagebox
#Frame:是tkinter框架控件,屏幕上会有个矩形区域,存放新增的东西
class Calculator(Frame):
    def __init__(self,master=None):
        # Frame.__init__(self,master,bg='red')
        Frame.__init__(self)
        self.pack(expand=YES, fill=BOTH) #要记得pack()的时候设置为全扩充
        # self.master.geometry("320x210+500+200")
        self.master.title('计算器')
        self.master.rowconfigure( 0, weight = 2 )
        self.master.columnconfigure( 0, weight = 2 )
        self.grid( sticky = W+E+N+S )
        text = Text(self, width=10, height=4)
        text.grid(row=0, column=0, columnspan=6, sticky= W+E+N+S)
        text.insert(INSERT, "\n")
        grid = '789+456-123*0./='
        for index, textChar in enumerate(grid):
            a = Button(self, text=textChar, width=8)
            if a["text"] != "+" and a["text"] != "-" and a["text"] != "*" and a["text"] != "/" and a["text"] != "=":
                a["command"] = lambda tt=textChar:text.insert(INSERT, tt)
            elif a["text"] != "=":
                a["command"] = lambda tt=textChar:[
                    #此处拐了个弯
                    #如果不加tt+"\n",如果输入12+34+,第一行的结果会是12+3412++
                    #加上tt+"\n",输入12+34+,输出的结果是12+34+换行符12++
                    #之后text.delete(2.0, END)删除了上面换行符后面的内容就只剩12+34+,之后在第二行插入过回车换行符
                    #text.insert(1.0, text.get(1.0, END).replace('\n', '')), //可以这样测试看看输出什么
                    text.insert(1.0, text.get(1.0, END).replace('\n', '') + tt + "\n"),
                    text.delete(2.0, END),
                    text.insert(2.0, "\n"),
                    #要达到计算器的效果,需要在这里插入表达式运算
                ]
            else:
                a["command"] = lambda tt=textChar:[
                    text.insert(1.0, text.get(1.0, END).replace('\n', '') + tt + "\n"),
                    text.delete(2.0, END),
                    text.insert(2.0, "\n"),
                    text.insert(2.0, eval(text.get(1.0, END).replace('\n', '')[:-1])) #表达式1+2+3=?   此处的-1是把=号去掉后进行运算,测试的时候有等号不能进行运算,会报错
                ]
            a.grid(row=2 + index // 4, column=index % 4)
            # if a["text"] == '=':
            #     a["command"]=lambda :text.insert("insert", "=\n"+str(eval(text.get(0.0, END))))
            b = Button(self, text="clear", width=8)
            b["command"] = lambda :text.delete(0.0, END)
            b.grid(row=2, column=5, rowspan=4, sticky=W+E+N+S)
if __name__ == '__main__':
    Calculator().mainloop() # 1 mainloop()方法允许程序循环执行,并进入等待和处理事件。 2、mainloop()方法的作用是监控每个组件,当组件发生变化或触发事件时,会立即更新窗口。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值