使用PySimpleGUI打造个人专属计算器

使用tkinter写GUI着实有些繁琐,三种布局方式调试得让人怀疑人生。那有没有布局简单一些的,让我们能将更多的精力放在处理逻辑上呢?那自然是有的,PySimpleGUI便是其中的佼佼者。下面用它来写个计算器的小案例。
先放张最终效果图吧:
在这里插入图片描述

实现步骤

流程并不复杂,两步即可。

  • 环境准备
    python 3.6.5
    pip install PySimpleGUI

  • 敲代码

'''
 @author:jxc
 @function:简易计算器
 @time:2020-7-11
'''
import math
import PySimpleGUI as psg

class Calculator:
    def __init__(self):
        self.result = '0' #计算结果
        self.express ='0'#表达式
        self.last_step = 'L'#上一步操作
    #窗口初始化
    def init_window(self):
        #按钮上的文字
        btn_texts = '清零,回退,x²,+/-|7,8,9,÷|4,5,6,x|1,2,3,-|.,0,=,+'
        #创建按钮
        btn_text_list = [ bt.split(',') for bt in btn_texts.split('|')]
        btn_list = [[psg.Button(button_text='%s'%bt,size=(6,2),pad=((5,5),(6,6))) for bt in btl] for btl in btn_text_list]
        #创建布局
        layout = [
            [psg.Text(text=self.express,justification='right',size=(30,1),pad=((5,5),(0,0)),font=('SimHei',11),background_color='#000',text_color='#fff',key='_express_')],
            [psg.Text(text=self.result,justification='right',size=(30,1),pad=((5,5),(0,0)),font=('SimHei',11),background_color='#000',text_color='#fff',key='_result_')]
        ]
        #将按钮加入布局
        for btn in btn_list:
            layout.append(btn)
        #创建窗口
        self.window = psg.Window(title='简易计算器',layout=layout,background_color='#faf8f8')

    #更新表达式
    def update_express(self):
        self.window['_express_'].update(self.express)
    #更新结果
    def update_result(self):
        #控制浮点数精度
        if '.' in str(self.result) and len(str(self.result))>10:
            self.result = round(self.result,4)
        self.window['_result_'].update(self.result)
    #弹出提示框
    def show_message(self,msg):
        psg.popup(msg)
    #计算
    def calculate(self):
        self.init_window()
        #循环阻塞监听
        while True:
            button,values = self.window.read() #监听动作
            #按 x 退出
            if button==None:
                break
            elif button=='清零':
                self.result = '0'
                self.express = '0'
                self.update_express()
                self.update_result()
            elif button=='回退':
                self.express = self.express[:-1] if len(self.express)>1 else '0'
                self.update_express()
            elif button=='x²':
                self.last_step = button
                try:
                    self.result = math.pow(float(self.express),2)
                    self.update_result()
                except Exception as e:
                    self.show_message('该表达式无法计算平方')
            elif button in '0123456789':
                if button=='0' and self.express[-1]=='÷':
                    self.show_message('0不能作除数')
                    continue
                self.express = self.express+button if self.express!='0' else button
                self.update_express()
                self.last_step = button
            elif button in '.+-x÷':
                if button=='.' and '.' in self.express+str(self.result):
                    continue
                if self.express[-1] in '.+-x÷':
                    self.express = self.express[:-1]+button
                elif self.last_step in '=x²':
                    self.express = str(self.result)+button
                else:
                    self.express+=button
                self.update_express()
                self.last_step = button
            elif button == '=':
                self.last_step = button
                try:
                    self.express = self.express.replace('x','*').replace('÷','/')
                    self.result = eval(self.express)
                    self.express = self.express.replace('*', 'x').replace('/', '÷')
                    self.update_result()
                except Exception as e:
                    self.show_message('该表达式无法进行计算')
            elif button =='+/-':
                try:
                    float(self.express)#判断是否是浮点数
                    self.express = '-'+self.express
                    self.update_express()
                except Exception as e:
                    self.show_message('该表达式无法转为负数')



if __name__ == '__main__':
    cal = Calculator()
    cal.calculate()

代码中都有注释,不明白的地方欢迎评论区留言讨论~

博主其他文章推荐:

[1] 【python实用特性】- 迭代、可迭代对象、迭代器

[2] 【python实用特性】- 列表生成式

[3] 【python实用特性】- yield生成器

[4] 【python实用特性】- 装饰器

[5] 【Matplotlib】-自定义坐标轴刻度完成20万+数据的可视化

[6] Python+selenium实现自动爬取实例

[7] python爬取豆瓣Top250-改进版

[8] requests设置请求头、代理

[9] requests使用session保持会话

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值