import tkinter as tk
from tkinter import *
from functools import partial
#读取数据
def get_input(entry,argu):
entry.insert(END,argu)
#删除数据
def back_input(entry):
input_len=len(entry.get())
if input_len>0:
entry.delete(input_len-1)
#清空数据
def clear(entry):
entry.delete(0,END)
#计算数据
def cal(entry):
input=entry.get()
ouput=str(eval(input.strip()))
clear(entry)
entry.insert(END,ouput)
root=tk.Tk()
root.title("计算器")
root.resizable(width=False,height=False)
entry=tk.Entry(root,justify="right",font=("微软雅黑",12))
entry.grid(row=0, column=0, columnspan=4, padx=5, pady=5)
myButton=partial(tk.Button,root,bg="#D5E0EE",activebackground="#E5E35B",padx=10, pady=3)
button_7=myButton(text="7",command=lambda :get_input(entry,'7'))
button_7.grid(row=1,column=0,pady=5)
button_8=myButton(text="8",command=lambda :get_input(entry,'8'))
button_8.grid(row=1,column=1,pady=5)
button_9=myButton(text="9",command=lambda :get_input(entry,'9'))
button_9.grid(row=1,column=2,pady=5)
button_add=myButton(text="+",command=lambda :get_input(entry,'+'))
button_add.grid(row=1,column=3,pady=5)
button_4=myButton(text="4",command=lambda :get_input(entry,'4'))
button_4.grid(row=2,column=0,pady=5)
button_5=myButton(text="5",command=lambda :get_input(entry,'5'))
button_5.grid(row=2,column=1,pady=5)
button_5=myButton(text="6",command=lambda :get_input(entry,'6'))
button_5.grid(row=2,column=2,pady=5)
button_sub=myButton(text="-",command=lambda :get_input(entry,'-'))
button_sub.grid(row=2,column=3,pady=5)
button_1=myButton(text="1",command=lambda :get_input(entry,'1'))
button_1.grid(row=3,column=0,pady=5)
button_2=myButton(text="2",command=lambda :get_input(entry,'2'))
button_2.grid(row=3,column=1,pady=5)
button_3=myButton(text="3",command=lambda :get_input(entry,'3'))
button_3.grid(row=3,column=2,pady=5)
button_mul=myButton(text="*",command=lambda :get_input(entry,'*'))
button_mul.grid(row=3,column=3,pady=5)
button_0=myButton(text="0",command=lambda :get_input(entry,'0'))
button_0.grid(row=4,column=0,columnspan=2,pady=5,padx=10,sticky = tk.W+tk.N+tk.E+tk.S)
button_dot=myButton(text=".",command=lambda :get_input(entry,'.'))
button_dot.grid(row=4,column=2,pady=5)
button_div=myButton(text="/",command=lambda :get_input(entry,'/'))
button_div.grid(row=4,column=3,pady=5)
button_back=myButton(text="back",command=lambda :back_input(entry))
button_back.grid(row=5,column=0,pady=5)
button_clear=myButton(text="C",command=lambda :clear(entry))
button_clear.grid(row=5,column=1,pady=5)
button_equal=myButton(text="=",command=lambda :cal(entry))
button_equal.grid(row=5,column=2,columnspan=2,pady=5,sticky=W+N+S+E)
root.mainloop()
tkinter-简单计算器
最新推荐文章于 2024-07-19 12:30:19 发布