当前位置:主页 > 软件编程 > Python代码 >

python tkinter 做个简单的计算器的方法

时间:2022-02-10 13:50:33 | 栏目:Python代码 | 点击:

背景

最近本菜鸡在学习 python GUI,从 tkinter 入门,想先做个小软件练习一下
思来想去,决定做一个 计算器

设计思路

首先,导入我们需要的包 ― tkinter,并通过 实例化一个 Tk 对象 创建窗口
因为我有点菜,目前还把控不好各组件的位置,所以窗口使用自动默认的大小

import tkinter as tk
import tkinter.messagebox
win = tkinter.Tk()
win.title("计算器")
win.mainloop()

大致 规划 各组件的 位置

我的目标是做成这个样子(最终效果)

大致规划好位置后,我创建了 四个 Frame,如下
u1s1,感觉两三个就够了

# 承载提示信息与输入框的框架
entry_frame = tk.Frame(win)
# 承载运算符号的框架
menu_frame = tk.Frame(win)
# 承载数字的框架
major_frame = tk.Frame(win)
# 承载等号的框架
cal_frame = tk.Frame(win)

entry_frame.pack(side="top")
menu_frame.pack(side="left")
major_frame.pack()
cal_frame.pack(side="right")

下面就做一个 输入框,分为两部分

t_label = tk.Label(entry_frame, text = "请输入 : ")
t_label.pack(side='left')
word_entry = tk.Entry(
    entry_frame,
    fg = "blue", # 输入字体颜色,设置为蓝色
    bd = 3, # 边框宽度
    width = 39, # 输入框长度
    justify = 'right' # 设置对齐方式为靠右
)
word_entry.pack()

然后在下面的左侧 排列运算符号

for char in ['+', '-', '×', '÷']:
    myButton(menu_frame, char, word_entry)

其中,myButton 类实例化一个按钮,并且当点击按钮时,输入框会出现相应的文本
当时遇到了问题 ― 点击按钮无法获得争取的按钮上的文本你, 解决后写了一篇博客,传送门

用相同的办法 列举各个数字

for i in range(4):
    num_frame = tk.Frame(major_frame)
    num_frame.pack()
    if i < 3:
        for count in range(3*i+1, 3*i+4):
            myButton(num_frame, count, word_entry, side=(i, count))
        continue
    myButton(num_frame, 0, word_entry, side=(i, 0))

当然,重置按钮和计算按钮 可不能忘
最后的计算就懒了一点,直接使用 entry.get() 获得要计算的式子,使用 eval() 函数计算,如果格式错误即弹窗提示

def calculate(entry):
    try:
        result = entry.get()
        # 如果输入框中不存在字符串,则 = 按钮不管用
        if result == '':
            return
        result = eval(result)
        entry.delete(0, "end")
        entry.insert(0, str(result))
    except:
        tkinter.messagebox.showerror("错误", "格式错误!\n请重新输入!")
reset_btn = tk.Button(
    cal_frame,
    text = '重置',
    activeforeground = "blue",
    activebackground = "pink",
    width = "13",
    command = lambda :word_entry.delete(0, "end")
).pack(side="left")
result_btn = tk.Button(
    cal_frame,
    text = '=',
    activeforeground = "blue",
    activebackground = "pink",
    width = "13",
    command = lambda :calculate(word_entry)
).pack(side="right")

全部代码

major.py

# -*- coding=utf-8 -*-
# @Time    : 2021/3/4 13:06
# @Author  : lhys
# @FileName: major.py

myName = r'''
    Welcome, my master!
    My Name is :
     ____                ____        ____        ____         ____              ______________
    |    |              |    |      |    |      |    \       /    |           /              /
    |    |              |    |      |    |      |     \     /     |          /              /
    |    |              |    |      |    |      |      \   /      |         /              /
    |    |              |    |      |    |       \      \_/      /         /       _______/
    |    |              |    |______|    |        \             /          \            \
    |    |              |                |         \           /            \            \
    |    |              |     ______     |          \         /              \            \
    |    |              |    |      |    |           \       /                \________    \
    |    |              |    |      |    |            |     |               /              /
    |    |_______       |    |      |    |            |     |              /              /
    |            |      |    |      |    |            |     |             /              /
    |____________|      |____|      |____|            |_____|            /______________/
    '''
print(myName)
import tkinter as tk
from tools import *

win = tk.Tk()
win.title('计算器')

entry_frame = tk.Frame(win)
menu_frame = tk.Frame(win)
major_frame = tk.Frame(win)
cal_frame = tk.Frame(win)

entry_frame.pack(side="top")
menu_frame.pack(side="left")
major_frame.pack()
cal_frame.pack()

# 输入框
t_label = tk.Label(entry_frame, text = "请输入 : ")
t_label.pack(side='left')
word_entry = tk.Entry(
    entry_frame,
    fg = "blue",
    bd = 3,
    width = 39,
    justify = 'right'
)
word_entry.pack()


# 菜单栏
for char in ['+', '-', '×', '÷']:
    myButton(menu_frame, char, word_entry)

button_side = ['right', 'left']

for i in range(4):
    num_frame = tk.Frame(major_frame)
    num_frame.pack()
    if i < 3:
        for count in range(3*i+1, 3*i+4):
            myButton(num_frame, count, word_entry, side=(i, count))
        continue
    myButton(num_frame, 0, word_entry, side=(i, 0))

reset_btn = tk.Button(
    cal_frame,
    text = '重置',
    activeforeground = "blue",
    activebackground = "pink",
    width = "13",
    command = lambda :word_entry.delete(0, "end")
).pack(side="left")
result_btn = tk.Button(
    cal_frame,
    text = '=',
    activeforeground = "blue",
    activebackground = "pink",
    width = "13",
    command = lambda :calculate(word_entry)
).pack(side="right")

win.mainloop()

tools.py

# -*- coding=utf-8 -*-
# @Time    : 2021/3/4 13:20
# @Author  : lhys
# @FileName: tools.py

import tkinter
import tkinter.messagebox

def calculate(entry):
    try:
        result = entry.get()
        if result == '':
            return
        result = eval(result)
        print(result)
        entry.delete(0, "end")
        entry.insert(0, str(result))
    except:
        tkinter.messagebox.showerror("错误", "格式错误!\n请重新输入!")

class myButton():
    def __init__(self, frame, text, entry, **kwargs):
        side = kwargs.get('side') if 'side' in kwargs else ()
        self.btn = tkinter.Button(
            frame,
            text = text,
            activeforeground="blue",
            activebackground="pink",
            width="13",
            command=lambda :entry.insert("end", text)
        )
        if side:
            self.btn.grid(row=side[0], column=side[1])
        else:
            self.btn.pack()

您可能感兴趣的文章:

相关文章