tkinter 创建可以输入复杂算式的计算器#
之前写过 使用 vscode 借助 PyQt5 设计一个计算器,我们可以发现 PyQt5 有点繁琐,本文使用 tkinter 以尽可能少的代码实现一个计算器:
from tkinter import Tk, StringVar, ttk
class App(Tk):
def __init__(self):
super().__init__()
self.result = StringVar()
self.result_label = ttk.Label(self, textvariable=self.result,
background='lightgreen', width=15)
self.cal_frame = ttk.Frame(self, relief='solid')
self.values = []
self.names = ['123+', '456-', '789×', 'C./=']
style = ttk.Style(self)
style.configure("BW.TLabel", foreground="black", background="lightblue", font='Times 14')
self.widgets = self.create_widgets(self.names)
def create_button(self, key):
widget = ttk.Label(self.cal_frame, text=key,
anchor='center',
width=5, relief='raise', style="BW.TLabel")
widget.bind('<1>', lambda event: self.get_value(event, key))
return widget
def create_widgets(self, names):
_widgets = [[self.create_button(key) for key in row] for row in names]
return _widgets
def layout(self):
self.result_label.grid(row=0, column=0, sticky='nsew')
self.cal_frame.grid(row=1, column=0, sticky='nsew')
for m, row in enumerate(self.widgets):
for n, widget in enumerate(row):
widget.grid(row=m, column=n, sticky='we')
def get_value(self, event, key):
self.values.append(key)
res = ''.join(self.values)
self.result.set(res)
if key == '=':
res = res.replace('×', '*')[:-1]
try:
self.result.set(eval(res))
except:
self.result.set('Error!')
finally:
self.values = []
elif key == 'C':
self.result.set('')
self.values = []
root = App()
root.layout()
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=2)
root.rowconfigure(1, weight=2)
root.cal_frame.rowconfigure(0, weight=2)
root.cal_frame.rowconfigure(1, weight=2)
root.cal_frame.rowconfigure(2, weight=2)
root.cal_frame.rowconfigure(3, weight=2)
root.cal_frame.rowconfigure(4, weight=2)
root.cal_frame.columnconfigure(0, weight=1)
root.cal_frame.columnconfigure(1, weight=1)
root.cal_frame.columnconfigure(2, weight=1)
root.cal_frame.columnconfigure(3, weight=1)
root.cal_frame.columnconfigure(4, weight=1)
root.mainloop()
如果输入的算式有误,会报错,比如,输入如下错误的算式:
显示结果为: