参考 PyDataMath-II。
先创建计算器的 Window:
import numpy as np
import PySimpleGUI as sg
# 字体设置
font_name = 'Franklin Gothic Book'
# 设置 Button 的配置
button_font = (font_name, 24)
bw = {'size':(7,2), 'font':button_font, 'button_color':("black","#F8F8F8")}
bt = {'size':(7,2), 'font':button_font, 'button_color':("black","#F1EABC")}
bo = {'size':(31,2), 'font':button_font, 'button_color':("black","#ECA527"), 'focus':True}
# 定义布局
layout = [
[sg.Text('计算器', size=(50,1), justification='right', background_color="#272533",
text_color='white', font=(font_name, 14, 'bold'))],
[sg.Text('0.0000', size=(18,1), justification='right', background_color='black',
text_color='red', font=('Digital-7',48), relief='sunken', key="_DISPLAY_")]
]
layout += [[sg.Button(str(name),**bw) for name in names]
for names in np.arange(1, 10).reshape((3,3))]
layout[-1] += [sg.Button("*",**bt)]
layout[-2] += [sg.Button("-",**bt)]
layout[-3] += [sg.Button("+",**bt)]
layout += [[sg.Button('0',**bw), sg.Button('.',**bw),
sg.Button('C',**bt), sg.Button('/',**bt)],
[sg.Button('=',**bo, bind_return_key=True)]]
# 创建 Window
window = sg.Window('Python 定制的计算器', layout=layout,
background_color="#272533", return_keyboard_events=True)
接着定义一些辅助函数:
# helper functions
def format_number():
'''create a consolidated string of numbers from front and back lists'''
return float(''.join(var['front']) + '.' + ''.join(var['back']))
def update_display(display_value):
'''update the calculator display after an event click'''
try:
window['_DISPLAY_'].update(value='{:,.4f}'.format(display_value))
except:
window['_DISPLAY_'].update(value=display_value)
# click events
def number_click(event):
'''number button button click event '''
global var
if var['decimal']:
var['back'].append(event)
else:
var['front'].append(event)
update_display(format_number())
def clear_click():
'''C button click event '''
global var
var['front'].clear()
var['back'].clear()
var['decimal'] = False
def operator_click(event):
''' + - / * button click event '''
global var
var['operator'] = event
try:
var['x_val'] = format_number()
except:
var['x_val'] = var['result']
clear_click()
def calculate_click():
''' equals button click event '''
global var
var['y_val'] = format_number()
try:
var['result'] = eval(str(var['x_val']) + var['operator'] + str(var['y_val']))
update_display(var['result'])
clear_click()
except:
update_display("ERROR! DIV/0")
clear_click()
最后,启动 GUI 界面:
var = {'front':[], 'back':[], 'decimal':False,
'x_val':0.0, 'y_val':0.0, 'result':0.0, 'operator':''}
while True:
event, values = window.read()
if event == None:
break
elif event in np.arange(10).astype('str'):
number_click(event)
elif event in ['Escape:27','C']: # 'Escape:27 for keyboard control
clear_click()
update_display(0.0)
var['result'] = 0.0
elif event in ['+','-','*','/']:
operator_click(event)
elif event == '=':
calculate_click()
elif event == '.':
var['decimal'] = True
elif event == '%':
update_display(var['result'] / 100.0)
window.close()
最终的效果图: