许多GUI将计算器作为示例,贴一张pySimpleGUI库编写的计算器代码。

import PySimpleGUI as sg
def button(text):#数字键盘
    return sg.B(text,size=(4,2),pad=(2,2),font=('黑体',18),button_color='black')
layout=[
           [sg.T('',key='-show-')],
           [sg.In('',key='-input-',size=(12,2),font=('黑体',28))],
           [button(i)for i in ['AC','(',')','%']],
           [button(i)for i in '123+'],
           [button(i)for i in '456-'],
           [button(i)for i in '789X'],
           [button(i)for i in '0.=÷']
        ]

window=sg.Window('计算器',layout)
while True:
    event,values=window.read() #窗口的读取,有两个返回值(1.事件  2.值)
    if event==None:#窗口关闭事件
        break
    if event in ('0123456789+-().'):
        window['-input-'].update(values['-input-']+event)
        window['-show-'].update('')#清空错误提示
    if event == 'X':
        window['-input-'].update(values['-input-']+'*')
        window['-show-'].update('')
    if event == '÷':
        window['-input-'].update(values['-input-']+'/')
        window['-show-'].update('')
    if event == '%':
        try:#除数为0错误处理
            window['-input-'].update(eval(values['-input-']+'/100'))
        except:
            window['-input-'].update('')
            window['-show-'].update('输入错误')
    if event == 'AC':
        window['-input-'].update('')
        window['-show-'].update('')
    if event == '=':
        try:
            window['-input-'].update(eval(values['-input-']))
        except:
            window['-input-'].update('')
            window['-show-'].update('输入错误')

window.close()

标签: python, pySimpleGUI

评论已关闭