学习Tkinter图形界面编程,编一个简单的计算器(二)——功能逻辑部分

avatar
(Edited)

上次的文章,其实上次的图形界面有个大bug,就是没有按键‘0’,赶紧给加上去,而且太矮胖了,美观和易用性都不行,继续改进下:

1.图形界面改进

按钮太扁了,那就考虑垫高一些,加个垫子(pad)吧:

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

padx是水平方向“加垫子”,pady是垂直方向“加垫子”。
显示数字的输入框太简陋了,加点有立体感的边框吧:

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

borderwidth就是设置边框宽度。
改进之后的计算器界面:
Image 2.jpg
图一:改进后的界面,增加了数字0键,加大了按键方便点击,美化了数字框。来源:本人截图。

2.编写功能逻辑

图形界面的功能简单表述就是,程序执行一个无限循环,不停的问“有没有人动我啊?”。如果有人碰了它,图形界面就会根据被碰到的部位,调用相应的功能。所以程序员要做的事就是编写功能代码,术语叫函数(Function)。然后把函数名称绑定到相应的部件上。
比如按键输入数字的功能:

def input_num(num):
    e.insert(END, num)
...
btn7=Button(root,text='7',padx=40,pady=20,command=lambda:input_num('7'))
btn8=Button(root,text='8',padx=40,pady=20,command=lambda:input_num('8'))
btn9=Button(root,text='9',padx=40,pady=20,command=lambda:input_num('9'))
btn4=Button(root,text='4',padx=40,pady=20,command=lambda:input_num('4'))
btn5=Button(root,text='5',padx=40,pady=20,command=lambda:input_num('5'))
btn6=Button(root,text='6',padx=40,pady=20,command=lambda:input_num('6'))
btn1=Button(root,text='1',padx=40,pady=20,command=lambda:input_num('1'))
btn2=Button(root,text='2',padx=40,pady=20,command=lambda:input_num('2'))
btn3=Button(root,text='3',padx=40,pady=20,command=lambda:input_num('3'))
btn0=Button(root,text='0',padx=40,pady=20,command=lambda:input_num('0'))

def input_num(num)就是接受键入数值的函数,在按钮部件(Button)的设定中加入命令参数(command=)来进行绑定,这里command=后面一般只能接函数名,不能带括号加
参数的。如果写成括号加参数,python解释器会在程序一启动时就执行而不会等到按键被按下才调用,所以这里变通的方式是用lambda打包一下。lambda函数叫匿名函数,直接用参数加表达式实现函数功能,不需要先定义再调用。
进行新的计算前要清除上次的计算结果,我们来看看这个功能如何编写和绑定:

def clear():
    e.delete(0,END)
...
btn_clear=Button(root,text='清除',padx=32,pady=20,command=clear)

这个就是标准的绑定了,command=后面接函数名clear,而不是clear()。delete和上面的insert是输入框自带的功能函数,delete(0,END)就是从最开始的位置0一直删到尾,全部清除。
下面我简单把剩下的编程思路简单说下:
在输入完第一个数字后,用户会按运算符键,这时候就把第一个数字用e.get()功能获得后,存入一个全局变量f_num里面,和其他程序语言一样,python语言的变量分全局和本地,全局变量任何函数都可以调取,但本地变量只能在本函数内部调取。f_num变量肯定还会被绑定给“=”键的函数用到,所以设为全局变量,同理,按下运算符键后,运算符也要保存在全局变量operator里,以便“=”键的函数调用,同时,按下运算符后还要把输入框清除干净,等待输入下一个数。而“=”的函数则使用一个条件判断语句,根据全局变量operator的功能对两个数进行运算,并返回结果。

计算器程序的全部代码如下:

#-*-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=Button(root,text='7',padx=40,pady=20,command=lambda:input_num('7'))
btn8=Button(root,text='8',padx=40,pady=20,command=lambda:input_num('8'))
btn9=Button(root,text='9',padx=40,pady=20,command=lambda:input_num('9'))
btn4=Button(root,text='4',padx=40,pady=20,command=lambda:input_num('4'))
btn5=Button(root,text='5',padx=40,pady=20,command=lambda:input_num('5'))
btn6=Button(root,text='6',padx=40,pady=20,command=lambda:input_num('6'))
btn1=Button(root,text='1',padx=40,pady=20,command=lambda:input_num('1'))
btn2=Button(root,text='2',padx=40,pady=20,command=lambda:input_num('2'))
btn3=Button(root,text='3',padx=40,pady=20,command=lambda:input_num('3'))
btn0=Button(root,text='0',padx=40,pady=20,command=lambda:input_num('0'))
btn_add=Button(root,text='+',padx=40,pady=20,command=lambda:operation('+'))
btn_sub=Button(root,text='-',padx=40,pady=20,command=lambda:operation('-'))
btn_product=Button(root,text='×',padx=40,pady=20,command=lambda:operation('×'))
btn_divide=Button(root,text='÷',padx=40,pady=20,command=lambda:operation('÷'))
btn_equal=Button(root,text='=',padx=40,pady=20,command=calculate)
btn_clear=Button(root,text='清除',padx=32,pady=20,command=clear)

#放置按键
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_add.grid(row=1,column=3)
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()

总共也就77行代码,学习起来还是比较简单了,当然这个计算器功能还非常简单,比如只能计算整数,每次计算前还需要清零。。。等等,这里只是通过这个小程序展示用python自带的Tkinter库编写程序有多么简单,希望读者看了这篇文章之后也可以自己编写自己需要的程序。
下面是计算器运行效果:
caculator.gif
图二:计算器使用效果 来源:本人录屏


参考资料



0
0
0.000
4 comments
avatar

你那里天气如何?想来玩目前STEEM上最火爆的drugwars游戏吗?还在等待什么?赶快加入战斗吧!drugwars.io感谢支持。

0
0
0.000
avatar

感谢代理101.33SP 给team-cn! 由于你使用CN作为你的首标签,额外获得2%点赞! 你的帖子获得team-cn 10% 点赞!(如果不想看到这个回复,请回复“取消”)

0
0
0.000
avatar

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

0
0
0.000
avatar


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.

For additional information please join us on the SteemSTEM discord and to get to know the rest of the community!

Please consider using the steemstem.io app and/or including @steemstem in the list of beneficiaries of this post. This could yield a stronger support from SteemSTEM.

0
0
0.000