使用python的tkinter库自制计算器ui界面

原理

tkinter库

主要使用label和button,具体了解看教程https://www.cnblogs.com/shwee/p/9427975.html

eval函数

这个函数能把字符串转化为代码执行,在这里对于简化代码很有帮助。
https://www.runoob.com/python/python-func-eval.html

源代码

import tkinter as tk
import tkinter.messagebox

root = tk.Tk()
root.title("calcutor")

equ = tk.StringVar()
equ.set("")

def backspace():
    var = equ.get()
    flag = 0
    flag += var.count("+")
    flag += var.count("-")
    flag += var.count("*")
    flag += var.count("/")
    if "=" in var and flag <= 1:
        k = var.index("=")
        equ.set(var[:k])
    else:
        equ.set(equ.get()[:-1])
    flag = 0
    
def show(push_var):
    equ.set(equ.get()+str(push_var))

def clear():
    equ.set("")

def calculate():
    var=equ.get()
    if "=" in var:
        k=var.index("=")
        equ.set(var[k+2:])
    try:
        result = eval(equ.get())
        equ.set(equ.get()+ "=\n" + str(result))
    except Exception:
        tkinter.messagebox.showerror(title='fail', message='check your input please')

l=tk.Label(root,bg='black',fg='white',width=25,height=2,relief="raised",textvariable=equ)
l.grid(row=0,column=0,padx=5,pady=5,columnspan=4)

tk.Button(root,text="C",width=5,command=clear).grid(row=1,column=0)
tk.Button(root,text="÷",width=5,command=lambda:show("/")).grid(row=1,column=1)
tk.Button(root,text="x",width=5,command=lambda:show("*")).grid(row=1,column=2)
tk.Button(root,text="DEL",width=5,command=backspace).grid(row=1,column=3)

tk.Button(root,text="7",width=5,command=lambda:show("7")).grid(row=2,column=0)
tk.Button(root,text="8",width=5,command=lambda:show("8")).grid(row=2,column=1)
tk.Button(root,text="9",width=5,command=lambda:show("9")).grid(row=2,column=2)
tk.Button(root,text="-",width=5,command=lambda:show("-")).grid(row=2,column=3)

tk.Button(root,text="4",width=5,command=lambda:show("4")).grid(row=3,column=0)
tk.Button(root,text="5",width=5,command=lambda:show("5")).grid(row=3,column=1)
tk.Button(root,text="6",width=5,command=lambda:show("6")).grid(row=3,column=2)
tk.Button(root,text="+",width=5,command=lambda:show("+")).grid(row=3,column=3)

tk.Button(root,text="1",width=5,command=lambda:show("1")).grid(row=4,column=0)
tk.Button(root,text="2",width=5,command=lambda:show("2")).grid(row=4,column=1)
tk.Button(root,text="3",width=5,command=lambda:show("3")).grid(row=4,column=2)
tk.Button(root,text="=",width=5,height=2,command=calculate).grid(row=4,column=3,rowspan=2)

tk.Button(root,text="%",width=5,command=lambda:show("%")).grid(row=5,column=0)
tk.Button(root,text="0",width=5,command=lambda:show("0")).grid(row=5,column=1)
tk.Button(root,text=".",width=5,command=lambda:show(".")).grid(row=5,column=2)


root.mainloop()

效果

在这里插入图片描述

细节

1.除法显示为"/"。
2.支持连续运算。
3.delet键删除会判断有几个运算符,然后再决定删除等号后的所有字符还是结尾一个字符。

posted @ 2022-09-08 09:33  弦masamasa  阅读(93)  评论(0编辑  收藏  举报