栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python Tkinter 伪科学计算器

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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()

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/965567.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号