Python Tkinter 伪科学计算器

期末大作业,功能有加减乘除、求余、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()

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值