# 学习Tkinter图形界面编程，编一个简单的计算器（二）——功能逻辑部分

in #cn2 years ago (edited)

## 1.图形界面改进

``````btn7=Button(root,text='7',padx=40,pady=20,command=lambda:input_num('7'))
``````

``````e=Entry(root,width=40,borderwidth=10)
``````

borderwidth就是设置边框宽度。

## 2.编写功能逻辑

``````def input_num(num):
e.insert(END, num)
...
``````

def input_num（num）就是接受键入数值的函数，在按钮部件（Button）的设定中加入命令参数（command=）来进行绑定，这里command=后面一般只能接函数名，不能带括号加

``````def clear():
e.delete(0,END)
...
``````

``````#-*-coding:utf-8 -*
from Tkinter import *

#数字输入
def input_num(num):
e.insert(END, num)

#清除按键的功能
def clear():
e.delete(0,END)

#运算符按键的功能
def operation(oper):
global f_num,operator
operator=oper
f_num=int(e.get())
e.delete(0,END)

#‘=’按键的功能
def calculate():
snd_num=int(e.get())
e.delete(0,END)
if operator=='+':
e.insert(END, str(f_num+snd_num))
elif operator=='-':
e.insert(END, str(f_num-snd_num))

elif operator=='×':
e.insert(END, str(f_num*snd_num))

elif operator=='÷':
e.insert(END, str(float(f_num)/snd_num))

root=Tk()
root.title('计算器')

e=Entry(root,width=40,borderwidth=10)
e.grid(row=0,column=0,columnspan=4)

#设置按键

#放置按键
btn7.grid(row=1,column=0)
btn8.grid(row=1,column=1)
btn9.grid(row=1,column=2)
btn4.grid(row=2,column=0)
btn5.grid(row=2,column=1)
btn6.grid(row=2,column=2)
btn1.grid(row=3,column=0)
btn2.grid(row=3,column=1)
btn3.grid(row=3,column=2)
btn0.grid(row=4,column=0)
btn_sub.grid(row=2,column=3)
btn_product.grid(row=3,column=3)
btn_divide.grid(row=4,column=3)
btn_equal.grid(row=4,column=2)
btn_clear.grid(row=4,column=1)

root.mainloop()
``````

## 参考资料

Sort:

JCAR 12 구독보팅입니다. 한 해 마지막 한달이네요. 소중한 시간, 유종의 미를 거두는 12월 되기를 응원합니다.

This post has been voted on by the SteemSTEM curation team and voting trail. It is elligible for support from @curie and @minnowbooster.

If you appreciate the work we are doing, then consider supporting our witness @stem.witness. Additional witness support to the curie witness would be appreciated as well.