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

python作业
python使用Tkiner做一个简单计算器_第1张图片

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

你可能感兴趣的:(python,开发语言)