话不多说,直接上代码:
import tkinter as tk
win3 = tk.Tk()
win3.title('简易计算器')
win3.geometry('400x300')
result_var = tk.StringVar()
def digit_click(num):
resul_show.insert('end',num)
def digit(x):
resul_show.insert('end',x)
def re():
opt_str = resul_show.get()
y = eval(opt_str)
resul_show.insert('end','='+ str(y))
def cls():
resul_show.delete(0,100)
resul_show = tk.Entry(win3,font='Arial 22',width=15,textvariable=result_var)
btn9 = tk.Button(win3, text='9', width=6, height=2,command=lambda :digit_click('9'))
btn8 = tk.Button(win3, text='8', width=6, height=2,command=lambda :digit_click('8'))
btn7 = tk.Button(win3, text='7', width=6, height=2,command=lambda :digit_click('7'))
btn6 = tk.Button(win3, text='6', width=6, height=2,command=lambda :digit_click('6'))
btn5 = tk.Button(win3, text='5', width=6, height=2,command=lambda :digit_click('5'))
btn4 = tk.Button(win3, text='4', width=6, height=2,command=lambda :digit_click('4'))
btn3 = tk.Button(win3, text='3', width=6, height=2,command=lambda :digit_click('3'))
btn2 = tk.Button(win3, text='2', width=6, height=2,command=lambda :digit_click('2'))
btn1 = tk.Button(win3, text='1', width=6, height=2,command=lambda :digit_click('1'))
btn0 = tk.Button(win3, text='0', width=6, height=2,command=lambda :digit_click('0'))
btn_point = tk.Button(win3, text='.', width=6, height=2, command=lambda :digit('.'))
btn_add = tk.Button(win3, text='+', width=6, height=2, command=lambda :digit('+'))
btn_equal = tk.Button(win3, text='=',width=6, height=2,command=re)
btn_sub = tk.Button(win3, text='-',width=6, height=2, command=lambda :digit('-'))
btn_cls = tk.Button(win3, text='Cls',width=6, height=5,command=lambda :cls())
resul_show.grid(row=0,column=0,columnspan=4)
btn9.grid(row=1,column=0)
btn8.grid(row=1, column=1)
btn7.grid(row=1, column=2)
btn6.grid(row=2, column=0)
btn5.grid(row=2, column=1)
btn4.grid(row=2, column=2)
btn3.grid(row=3, column=0)
btn2.grid(row=3, column=1)
btn1.grid(row=3, column=2)
btn0.grid(row=4, column=0)
btn_cls.grid(row=1,rowspan=2,column=3)
btn_sub.grid(row=3,column=3)
btn_point.grid(row=4, column=1)
btn_add.grid(row=4, column=2)
btn_equal.grid(row=4, column=3)
win3.mainloop()
运行效果图如下:
如有不对之处,欢迎各位的指正,
有更好的方法,欢迎评论区交流。
如有不懂之处在评论区写出,感谢观看!