python简单计算器

本文介绍了一个使用PythonPySimpleGUI库实现的简单计算器应用,包括输入验证、基本运算符处理和结果计算功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

附赠源码:

import PySimpleGUI as sg
import re

listsNumber = [
    ['AC', '(', ')', '%'],
    [1, 2, 3, '+'],
    [4, 5, 6, '-'],
    [7, 8, 9, 'x'],
    [0, '.', '=', '÷'],
]

layout = [
    [sg.Text(font=('黑体', '10'), key='-msg-')],
    [sg.Multiline(
        '',
        key='-show-',
        s=(22, 10),
        font=('黑体', 14),
        border_width=1,
        expand_x=True,
        expand_y=True,
        pad=((0, 0), (5, 8)),
        background_color='black',
        text_color='white',
        no_scrollbar=True
    )],
    [[sg.Button(
        v,
        button_color='black' if v != 'AC' else 'red',
        pad=((2, 2), (2, 2)),
        size=(2, 1.5),
        font=('黑体', '12')

    ) for v in values] for values in listsNumber],
    [sg.Text(font=('黑体', '9'), key='-disassemble-')]
]

window = sg.Window(
    'http://www.seedtree.cn simpleGUI',
    layout,
    font=('宋体', 14)
)

hideVale = []  # 输入队列
errMsg = '输入错误,请重新输入!Input error, please re-enter'

def checkInput(strVal):
    if strVal in ['(', ')', '%', '+', '-', 'x', '÷', '.']:
        return True
    else:
        return False


# 是否需要清楚计算输入框内容
clearInputShow = False

while True:
    event, values = window.read()
    print(event)
    window['-msg-'].update('')
    print(clearInputShow)
    if clearInputShow and event is not None:
        window['-show-'].update(value='')
        clearInputShow = False
    # 符合重复输入
    if len(hideVale) > 0 and checkInput(hideVale[-1]) and checkInput(event):
        if checkInput(hideVale[-1]) and event == '(':
            print('#(#')
        elif hideVale[-1] == ')':
            print('#)#')
        else:
            continue
    if event == 'AC':
        window['-show-'].update("")
        hideVale = []
    if event in list('0123456789()+-.'):
        if len(hideVale) <= 0:
            hideVale.append(event)
        else:
            pattern = r"^[+-]?\d+(\.\d+)?$"
            if event in list('0123456789.') and re.match(pattern, hideVale[-1]):
                hideVale[-1] = '{}{}'.format(hideVale[-1], event)
            else:
                hideVale.append(event)
        window['-show-'].update(window['-show-'].get() + event)
    if event == 'x':
        window['-show-'].update(window['-show-'].get() + 'x')
        hideVale.append('*')
    if event == '÷':
        window['-show-'].update(window['-show-'].get() + '÷')
        hideVale.append('/')
    if event == '%':
        try:
            lastVal = hideVale[-1]
            window['-show-'].update(window['-show-'].get() + '%')
            del hideVale[-1]
            hideVale.append('({}/100)'.format(lastVal))
        except:
            window['-msg-'].update(errMsg, text_color='red')
            window['-show-'].update('')
            hideVale = []
    if event == '=':
        clearInputShow = True
        try:
            v = ''
            for i in hideVale:
                v += i
            window['-disassemble-'].update(v)
            window['-show-'].update(value="{} = {}".format(window['-show-'].get(), eval(v)))
        except:
            window['-msg-'].update(errMsg, text_color='red')
            window['-show-'].update('')
        finally:
            clearInputShow = True
            hideVale = []
    print(hideVale)
    if event is None:
        break

window.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刘贤松

一本万利

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值