用python gui实现计算器

源代码

from tkinter import Tk, Label, RAISED, Button, Entry,END
from tkinter.messagebox import showinfo

建立窗口

root = Tk()

定义各个函数,在输入框中弹出返回值

def num1():
jianru.insert([END], '1')
def cal():
a = jianru.get()
try:
b = eval(a)
jianru.delete(0,END)
jianru.insert(END,'{}'.format(b))
except:
showinfo(message= '输入格式错误')
def num2():
jianru.insert(END,'2')
def num3():
jianru.insert(END,'3')
def num4():
jianru.insert(END,'4')
def num5():
jianru.insert(END,'5')
def num6():
jianru.insert(END,'6')
def num7():
jianru.insert(END,'7')
def num8():
jianru.insert(END,'8')
def num9():
jianru.insert(END,'9')
def num0():
jianru.insert(END,'0')
def add():
jianru.insert(END,'+')
def deli():
jianru.insert(END,'-')
def cheng():
jianru.insert(END,'*')
def chu():
jianru.insert(END,'/')
def chongzhi():
jianru.delete(0,END)

建立输入框

jianru = Entry(root, width=20,)
jianru.grid(row = 0,column = 1)

建立按钮

buttom1 = Button(root, width=10, height=2, text = '1', command=num1)
buttom1.grid(row = 1,column = 0)
buttom2 = Button(root, width=10, height=2, text = '2', command=num2)
buttom2.grid(row = 1,column = 1)
buttom3 = Button(root, width=10, height=2, text = '3', command=num3)
buttom3.grid(row = 1,column = 2)
buttom_add = Button(root, width=10, height=2, text = '+', command=add)
buttom_add.grid(row = 1,column =3 )
buttom4 = Button(root, width=10, height=2, text = '4', command=num4)
buttom4.grid(row = 2,column =0 )
buttom5 = Button(root, width=10, height=2, text = '5', command=num5)
buttom5.grid(row = 2,column =1 )
buttom6 = Button(root, width=10, height=2, text = '6', command=num6)
buttom6.grid(row = 2,column =2 )
buttom_deli = Button(root, width=10, height=2, text = '-', command=deli)
buttom_deli.grid(row = 2,column =3 )
buttom7 = Button(root, width=10, height=2, text = '7', command=num7)
buttom7.grid(row = 3,column =0 )
buttom8 = Button(root, width=10, height=2, text = '8', command=num8)
buttom8.grid(row = 3,column =1 )
buttom9 = Button(root, width=10, height=2, text = '9', command=num9)
buttom9.grid(row = 3,column =2 )
buttom_cheng = Button(root, width=10, height=2, text = '*', command=cheng)
buttom_cheng.grid(row = 3,column =3 )
buttom_chongzhi = Button(root, width=10, height=2, text = '重置', command=chongzhi)
buttom_chongzhi.grid(row = 4,column =0 )
buttom0 = Button(root, width=10, height=2, text = '0', command=num0)
buttom0.grid(row = 4,column =1 )
buttom_dengyu = Button(root, width=10, height=2, text = '=', command=cal)
buttom_dengyu.grid(row = 4,column =2 )
buttom_chu = Button(root, width=10, height=2, text = '/', command=chu)
buttom_chu.grid(row = 4,column =3 )

将窗口置顶

root.mainloop()

代码运行

posted @ 2020-12-12 14:43  20201325my  阅读(421)  评论(0编辑  收藏  举报