python使用Tkiner做一个简单计算器

python作业
在这里插入图片描述

import tkinter as tk
import math

root = tk.Tk()
root.geometry('350x330+400+400')
root.title('简单计算器')
root.resizable(False, False)

text_area = tk.StringVar()
font = ('宋体', 20)
font_16 = ('宋体', 16)

frame_upper = tk.Frame(relief=tk.SUNKEN)
frame_upper.grid(row=0, column=0, columnspan=2)

frame_upper_sec = tk.Frame()
frame_upper_sec.grid(row=1, column=0, columnspan=2)

frame_low_left = tk.Frame()
frame_low_left.grid(row=2, column=0)

frame_low_right = tk.Frame()
frame_low_right.grid(row=2, column=1)

text_area = tk.StringVar()

text = tk.Label(frame_upper, textvariable=text_area, font=font, height=1, relief=tk.SUNKEN, width=22, anchor=tk.E)
text.pack(pady=4)


def set_content(content):
    text = text_area.get()
    text += str(content)
    text_area.set(text)


def get_fun(fun, content):
    def inner():
        fun(content)

    return inner


ls = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [9, '.', 'Sqrt']
]


def calc_sqrt():
    content = text_area.get()
    if len(content) > 0:
        result = eval(content)
        text_area.set(math.sqrt(result))


for i in range(4):
    for j in range(3):
        button = tk.Button(frame_low_left, text=str(ls[i][j]), width=5, font=font_16, relief=tk.RAISED)
        button.grid(row=i, column=j, padx=12, pady=12)
        if i == 3 and j == 2:
            button.config(command=calc_sqrt)
        else:
            button.config(command=get_fun(set_content, ls[i][j]))

ls_opp = ['+', '-', '*', '/', '**', '//']
for i in range(6):
    button = tk.Button(frame_low_right, text=ls_opp[i], width=5, font=font_16, relief=tk.RAISED, bg='orange')
    button.grid(row=i, padx=4, pady=0)
    button.config(command=get_fun(set_content, ls_opp[i]))

sec = ['清除', '=']


def clear(area):
    area.set('')


def calc():
    content = text_area.get()
    if len(content) > 0:
        content = eval(str(text_area.get()))
        text_area.set(content)


for i in range(2):
    button = tk.Button(frame_upper_sec, text=sec[i], width=8, font=font_16, relief=tk.RAISED,
                       bg=('pink' if i == 0 else 'yellow'))
    button.grid(row=0, column=i, padx=26, pady=4)
    if i == 0:
        button.config(command=lambda: clear(text_area))
    else:
        button.config(command=calc)

text_area.set('')

root.mainloop()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值