期末大作业,功能有加减乘除、求余、sin、cos、平方、阶乘、添加左右括号.
界面大小全局可调,按钮大小全局可调
(tkinter是真难用)
先看效果图:
python代码:
import ctypes
from tkinter import *
from math import sin
from math import cos
from math import tan
from math import log as ln
from math import factorial as fact
calculated = False
FONT_SIZE = 15 # 全局大小可调
BUTTON_SIZE = (8, 2) # 全局按钮大小
def act(name):
global calculated
if calculated:
calculated = False
text.set('')
if '0' <= name <= '9' or name in ['+', '-', '*', '/', '%', 'sin', 'cos', '(', ')', '.']:
text.set(text.get() + name)
elif name == 'X²':
text.set(text.get() + '**2')
elif name == 'x!':
text.set(text.get() + 'fact')
elif name == 'AC':
text.set('')
elif name == 'DEL':
text.set(text.get()[:-1])
else: # 计算
try:
result = eval(text.get())
text.set(text.get() + "=\n" + str(result))
except Exception:
text.set('Error!')
calculated = True
def add_button(name, row, col):
global root, FONT_SIZE, BUTTON_SIZE
Button(root, text=name, width=BUTTON_SIZE[0], height=BUTTON_SIZE[1], command=lambda: act(name),
font=("Arial", FONT_SIZE)).grid(row=row, column=col)
root = Tk()
root.title("我的计算器")
ctypes.windll.shcore.SetProcessDpiAwareness(1)
# 调用api获得当前的缩放因子
ScaleFactor = ctypes.windll.shcore.GetScaleFactorForDevice(0)
# 设置缩放因子
root.tk.call('tk', 'scaling', ScaleFactor / 75)
text = StringVar()
text.set('')
label = Label(root, width=BUTTON_SIZE[0] * 5, height=BUTTON_SIZE[1], padx=23, relief="raised", anchor=SE, textvariable=text,
font=("Arial", FONT_SIZE))
label.grid(row=0, column=0, columnspan=5, sticky='nw')
buttons = [
['x!', 'AC', 'DEL', '%', '/'],
['sin', '7', '8', '9', '*'],
['cos', '4', '5', '6', '-'],
['(', '1', '2', '3', '+'],
[')', 'X²', '0', '.', '='],
]
for i in range(len(buttons)):
for j in range(len(buttons[0])):
add_button(buttons[i][j], i + 1, j)
root.mainloop()