自学python-tkinter-计算器

用tkinter编写计算器:

1. 输入显示和按键的画图布置(此部分熟悉tkinter用法即可)

2. 输入和运算的函数(此部分需细心些,注意多考虑些逻辑和输入遇到的问题)

3. 将布图和函数整合成完整的代码

下面代码为:布图

'''
图框布置:1.显示基框 2.按键基框

'''
from tkinter import * 
# import tkinter  用此导入调用后面的Frame以及其他类需要添加tkinter.前缀

tk = Tk()
tk.geometry('480x500') # 定义面板最大的值:max_x * max_y
tk.title('计算器') # 定义标题
'''
画显示框
'''
jsq_show = Frame(width=600, height=300, bg='#dddddd')
jsq_show.pack()

sv = StringVar()
#sv.set('调试状态')
sv.set([1,2,3]+['*']+[4,5,6])

show_label = Label(jsq_show, textvariable=sv, bg='#eeeeee',width=34,height=4,
                   font=('黑体',18,'bold',),justify=LEFT,anchor='e')
show_label.pack(padx=10,pady=10)  
#  padx 表示到外边框的距离,不能小于多少  
# ipadx 表示到内边框的距离,不能小于多少                       

'''
画按键框
'''
jsq_aj = Frame(width=600, height=350, bg='#cccccc')
jsq_aj.pack()

def num(n):
    print(n)

def reset():
    print('重置')

def operation(n):
    print(n)
    
def str_delete():
    print('')
    
def result():
    print('=')

w = 5
h = 1
#  注意此处command,需要用到lambda
#  command=num('1')还没按键,就已经执行num('1')了
key_1 = Button(jsq_aj,text='1',width=w,height=h,command=lambda: num('1'),  bg='yellow',font=('黑体',30,'bold'))
key_1.grid(row=1,column=0)

key_2 = Button(jsq_aj,text='2',width=w,height=h,command=lambda: num('2'),bg='yellow',font=('黑体',30,'bold'))
key_2.grid(row=1,column=1)

key_3 = Button(jsq_aj,text='3',width=w,height=h,command=lambda: num('3'),bg='yellow',font=('黑体',30,'bold'))
key_3.grid(row=1,column=2)

key_4 = Button(jsq_aj,text='4',width=w,height=h,command=lambda: num('4'),bg='yellow',font=('黑体',30,'bold'))
key_4.grid(row=2,column=0)

key_5 = Button(jsq_aj,text='5',width=w,height=h,command=lambda: num('5'), bg='yellow',font=('黑体',30,'bold'))
key_5.grid(row=2,column=1)

key_6 = Button(jsq_aj,text='6',width=w,height=h,command=lambda: num('6'),bg='yellow',font=('黑体',30,'bold'))
key_6.grid(row=2,column=2)

key_7 = Button(jsq_aj,text='7',width=w,height=h,command=lambda: num('7'),bg='yellow',font=('黑体',30,'bold'))
key_7.grid(row=3,column=0)

key_8 = Button(jsq_aj,text='8',width=w,height=h,command=lambda: num('8'),bg='yellow',font=('黑体',30,'bold'))
key_8.grid(row=3,column=1)

key_9 = Button(jsq_aj,text='9',width=w,height=h,command=lambda: num('9'),bg='yellow',font=('黑体',30,'bold'))
key_9.grid(row=3,column=2)

key_0 = Button(jsq_aj,text='0',width=w,height=h,command=lambda: num('0'),bg='yellow',font=('黑体',30,'bold'))
key_0.grid(row=4,column=1)

key_point = Button(jsq_aj,text='.',width=w,height=h,command=lambda: num('.'),bg='yellow',font=('黑体',30,'bold'))
key_point.grid(row=4,column=2)

key_pms = Button(jsq_aj,text='± ',width=w,height=h,command=lambda:operation('±'),bg='yellow',font=('黑体',30,'bold'))
key_pms.grid(row=3,column=3)

key_close = Button(jsq_aj,text='close',width=w,height=h,bg='yellow',font=('黑体',30,'bold'))
key_close.grid(row=4,column=0)

key_plus = Button(jsq_aj,text='',width=w,height=h,command=lambda:operation('+'),bg='yellow',font=('黑体',30,'bold'))
key_plus.grid(row=1,column=3)

key_minus = Button(jsq_aj,text='-',width=w,height=h,command=lambda:operation('-'),bg='yellow',font=('黑体',30,'bold'))
key_minus.grid(row=2,column=3)

key_multiply = Button(jsq_aj,text='x',width=w,height=h,command=lambda:operation('x'),bg='yellow',font=('黑体',30,'bold'))
key_multiply.grid(row=0,column=2)

key_divide = Button(jsq_aj,text='÷',width=w,height=h,command=lambda:operation('÷'),bg='yellow',font=('黑体',30,'bold'))
key_divide.grid(row=0,column=1)

key_equal = Button(jsq_aj,text='=',width=w,height=h,command=result,bg='yellow',font=('黑体',30,'bold'))
key_equal.grid(row=4,column=3)

key_c = Button(jsq_aj,text='c',width=w,height=h,command=data_empty,bg='yellow',font=('黑体',30,'bold'))
key_c.grid(row=0,column=0)

key_del = Button(jsq_aj,text='',width=w,height=h,command=str_delete,bg='yellow',font=('黑体',30,'bold'))
key_del.grid(row=0,column=3)


tk.mainloop()

下面代码为:输入和运算函数

from tkinter import *

'''
输入显示与运算逻辑

'''
tk = Tk()


# 数据初始化
num1 = ''
num2 = ''
pms1 = []
pms2 = []
num1_list = []
num2_list = []
operat = []

'''
±号的输入:
1.通过判断运算符是否为空(operat==[''])来确定加在num1或num2前
2.确定num1后,再通过±号是否为空(pms1==[])来确定±号(+号为:'')
3.num2同上

'''
sv = StringVar()
sv.set('')  # 显示函数

def pms():
    if operat == []:
        num1_pms()
    else:
        num2_pms()

def num1_pms():
    if pms1 == []:
        pms1 = ['-']
        sv.set(pms1+num1_list+operat+pms2+num2_list) 
        # 上表达式是显示输入结果
    else:
        pms1 = []
        sv.set(pms1+num1_list+operat+pms2+num2_list)
    
def num2_pms():
    if pms2 == []:
        pms2 = ['-']
        sv.set(pms1+num1_list+operat+pms2+num2_list)
    else:
        pms2 = []
        sv.set(pms1+num1_list+operat+pms2+num2_list)
        

'''
数字的输入:(也包括'.'号)
1. 通过判断(operat==[''])来确定对象是num1(num2)
2. '.'需要通过判断('.' in num1_list )进行添加 
'''
def num_in(n):
    if operat == []:
        num1_in(n)
    else:
        num2_in(n)
        
def num1_in(n):
    if n == '.' and n in num1_list:
        pass    
    else:
        num1_list.append(n)
        sv.set(pms1+num1_list+operat+pms2+num2_list)

def num2_in(n):
    if n == '.' and n in num2_list:
        pass    
    else:
        num2_list.append(n)
        sv.set(pms1+num1_list+operat+pms2+num2_list)

'''
运算符(+,-,*,/)输入

'''
def operat_in(op): 
    # '0.'或者'.0'都是可以辨认的,'.'不行
    if num1_list==[] or num1_list==['.']:
        pass
    else:
        if operat == []:
            operat.append(op)
        else:
            pass        
        
'''
数据清空

'''
def data_empty():
    num1 = ''
    num2 = ''
    pms1 = []
    pms2 = []
    num1_list = []
    num2_list = []
    operat = []
    sv.set(pms1+num1_list+operat+pms2+num2_list)
    
'''
数据逐渐移除:

'''
def str_delete():
    if num2_list != []:
        l = len(num2_list)
        num2_list.remove(num2_list[l-1])
        sv.set(pms1+num1_list+operat+pms2+num2_list)
    
    elif num2_list==[] and pms2 !=[]:
        pms2 = []
        sv.set(pms1+num1_list+operat+pms2+num2_list)
        
    elif num2_list==[] and pms2==[] and operat !=[]:
        operat = []
        sv.set(pms1+num1_list+operat+pms2+num2_list)
    
    elif operat==[] and num1_list !=[]:
        l = len(num1_list)
        num1_list.remove(num1_list[l-1])
        sv.set(pms1+num1_list+operat+pms2+num2_list)
    
    elif num1_list==[] and pms1 !=[]:
        pms1 = []
        sv.set(pms1+num1_list+operat+pms2+num2_list)
        
    else:
        pass

'''
求值前将列表转成数字

'''    
    
def num_pro(n):
    if n == n1:
        # 判断±号
        if pms1 !=[]:
            num1 = pms1[0]
        else:
            num1 = ''
        # 将列转成字符串
        for i in num1_list:
            num1 += i
        # 判断小数点
        if '.' in num1_list:
            num1 = float(num1)
        else:
            num1 = int(num1)
                
    else: 
        if pms2 !=[]:
            num2 = pms2[0]
        else:
            num2 = ''
            
        for i in num2_list:
            num2 += i
            
        if '.' in num2list:
            num2= float(num2)
        else:
            num2= int(num2)
    
'''
求值

'''

def result():
    # 如果输入程序逻辑没问题,此处只需判断num2_list就够了
    if num2_list==[] or num2_list==['.']: 
        pass
    
    else:  
        num_pro(n1) 
        num_pro(n2)
        if operat == ['+']:
            r = num1 + num2
            data_empty()
            num1_list = list(str(r))
            # 之前用的num1_list.append(str(r)),有问题:
            # 后续在用num1_list时,无法识别其中的'.'
            sv.set(pms1+num1_list+operat+pms2+num2_list)
            
            
            
        if operat == ['-']:
            r = num1 - num2
            data_empty()
            num1_list = list(str(r))
            sv.set(pms1+num1_list+operat+pms2+num2_list)
            
        if operat == ['x']:
            r = num1 * num2
            data_empty()
            num1_list = list(str(r))
            sv.set(pms1+num1_list+operat+pms2+num2_list)        

        if operat == ['÷']:
            r = num1 / num2
            data_empty()
            num1_list = list(str(r))
            sv.set(pms1+num1_list+operat+pms2+num2_list)
        

'''
关闭

'''        
def close():
    tk.destroy()
        

        

tk.mainloop()

完整的计算器代码:

from tkinter import *
import math


class calculator():

    def __init__(self):
        global tk
        tk = Tk()  # 注意不能用self = Tk(),相当于将子类重新赋值了
        tk.geometry('480x500')
        tk.title('计算器')

        show = Frame(width=600, height=300, bg='#dddddd')
        show.pack()
        self.sv = StringVar()
        self.sv.set('初始状态')

        show_label = Label(show, textvariable=self.sv, bg='#eeeeee', width=34, height=4,
                           font=('黑体', 18, 'bold',), justify=LEFT, anchor='e')
        show_label.pack(padx=10, pady=10)

        k_area = Frame(width=600, height=350, bg='#cccccc')
        k_area.pack()

        # 数据初始化
        self.num1 = ''
        self.num2 = ''
        self.pms1 = []
        self.pms2 = []
        self.num1_list = []
        self.num2_list = []
        self.operat = []

        w = 5
        h = 1

        key_1 = Button(k_area, text='1', width=w, height=h, command=lambda: self.num_in('1'),
                       bg='yellow', font=('黑体', 30, 'bold'))
        key_1.grid(row=1, column=0)

        key_2 = Button(k_area, text='2', width=w, height=h, command=lambda: self.num_in('2'),
                       bg='yellow', font=('黑体', 30, 'bold'))
        key_2.grid(row=1, column=1)

        key_3 = Button(k_area, text='3', width=w, height=h, command=lambda: self.num_in('3'),
                       bg='yellow', font=('黑体', 30, 'bold'))
        key_3.grid(row=1, column=2)

        key_4 = Button(k_area, text='4', width=w, height=h, command=lambda: self.num_in('4'),
                       bg='yellow', font=('黑体', 30, 'bold'))
        key_4.grid(row=2, column=0)

        key_5 = Button(k_area, text='5', width=w, height=h, command=lambda: self.num_in('5'),
                       bg='yellow', font=('黑体', 30, 'bold'))
        key_5.grid(row=2, column=1)

        key_6 = Button(k_area, text='6', width=w, height=h, command=lambda: self.num_in('6'),
                       bg='yellow', font=('黑体', 30, 'bold'))
        key_6.grid(row=2, column=2)

        key_7 = Button(k_area, text='7', width=w, height=h, command=lambda: self.num_in('7'),
                       bg='yellow', font=('黑体', 30, 'bold'))
        key_7.grid(row=3, column=0)

        key_8 = Button(k_area, text='8', width=w, height=h, command=lambda: self.num_in('8'),
                       bg='yellow', font=('黑体', 30, 'bold'))
        key_8.grid(row=3, column=1)

        key_9 = Button(k_area, text='9', width=w, height=h, command=lambda: self.num_in('9'),
                       bg='yellow', font=('黑体', 30, 'bold'))
        key_9.grid(row=3, column=2)

        key_0 = Button(k_area, text='0', width=w, height=h, command=lambda: self.num_in('0'),
                       bg='yellow', font=('黑体', 30, 'bold'))
        key_0.grid(row=4, column=1)

        key_point = Button(k_area, text='.', width=w, height=h, command=lambda: self.num_in('.'),
                           bg='yellow', font=('黑体', 30, 'bold'))
        key_point.grid(row=4, column=2)

        key_pms = Button(k_area, text='±', width=w, height=h, command=self.pms,
                         bg='yellow', font=('黑体', 30, 'bold'))
        key_pms.grid(row=3, column=3)

        key_close = Button(k_area, text='Close', width=w, height=h, bg='red', command=self.close,
                           font=('黑体', 30, 'bold'))
        key_close.grid(row=4, column=0)

        key_plus = Button(k_area, text='+', width=w, height=h, command=lambda: self.operat_in('+'),
                          bg='yellow', font=('黑体', 30, 'bold'))
        key_plus.grid(row=1, column=3)

        key_minus = Button(k_area, text='-', width=w, height=h, command=lambda: self.operat_in('-'),
                           bg='yellow', font=('黑体', 30, 'bold'))
        key_minus.grid(row=2, column=3)

        key_multiply = Button(k_area, text='x', width=w, height=h, command=lambda: self.operat_in('x'),
                              bg='yellow', font=('黑体', 30, 'bold'))
        key_multiply.grid(row=0, column=2)

        key_divide = Button(k_area, text='÷', width=w, height=h, command=lambda: self.operat_in('÷'),
                            bg='yellow', font=('黑体', 30, 'bold'))
        key_divide.grid(row=0, column=1)

        key_equal = Button(k_area, text='=', width=w, height=h, command=self.result,
                           bg='yellow', font=('黑体', 30, 'bold'))
        key_equal.grid(row=4, column=3)

        key_c = Button(k_area, text='Clear', width=w, height=h, command=self.data_empty,
                       bg='yellow', font=('黑体', 30, 'bold'))
        key_c.grid(row=0, column=0)

        key_del = Button(k_area, text='', width=w, height=h, command=self.str_delete,
                         bg='yellow', font=('黑体', 30, 'bold'))
        key_del.grid(row=0, column=3)

        tk.mainloop()

    def pms(self):
        if self.operat == []:
            self.num1_pms()
        else:
            self.num2_pms()

    def num1_pms(self):
        if self.pms1 == []:
            self.pms1 = ['-']
            self.sv.set(self.pms1 + self.num1_list + self.operat + self.pms2 + self.num2_list)
        else:
            self.pms1 = []
            self.sv.set(self.pms1 + self.num1_list + self.operat + self.pms2 + self.num2_list)

    def num2_pms(self):
        if self.pms2 == []:
            self.pms2 = ['-']
            self.sv.set(self.pms1 + self.num1_list + self.operat + self.pms2 + self.num2_list)
        else:
            self.pms2 = []
            self.sv.set(self.pms1 + self.num1_list + self.operat + self.pms2 + self.num2_list)

    def num_in(self, n):
        if self.operat == []:
            self.num1_in(n)
        else:
            self.num2_in(n)

    def num1_in(self, n):
        if n == '.' and n in self.num1_list:
            pass
        else:
            self.num1_list.append(n)
            self.sv.set(self.pms1 + self.num1_list + self.operat + self.pms2 + self.num2_list)

    def num2_in(self, n):
        if n == '.' and n in self.num2_list:
            pass
        else:
            self.num2_list.append(n)
            self.sv.set(self.pms1 + self.num1_list + self.operat + self.pms2 + self.num2_list)

    def operat_in(self, op):
        if self.num1_list == [] or self.num1_list == ['.']:
            pass
        else:
            if self.operat == []:
                self.operat.append(op)
                self.sv.set(self.pms1 + self.num1_list + self.operat + self.pms2 + self.num2_list)
            else:
                pass

    def data_empty(self):
        self.num1 = ''
        self.num2 = ''
        self.pms1 = []
        self.pms2 = []
        self.num1_list = []
        self.num2_list = []
        self.operat = []
        self.sv.set(self.pms1 + self.num1_list + self.operat + self.pms2 + self.num2_list)

    def str_delete(self):
        if self.num2_list != []:
            l = len(self.num2_list)
            self.num2_list.remove(self.num2_list[l - 1])
            self.sv.set(self.pms1 + self.num1_list + self.operat + self.pms2 + self.num2_list)
        elif self.num2_list == [] and self.pms2 != []:
            self.pms2 = []
            self.sv.set(self.pms1 + self.num1_list + self.operat + self.pms2 + self.num2_list)
        elif self.num2_list == [] and self.pms2 == [] and self.operat != []:
            self.operat = []
            self.sv.set(self.pms1 + self.num1_list + self.operat + self.pms2 + self.num2_list)
        elif self.operat == [] and self.num1_list != []:
            l = len(self.num1_list)
            self.num1_list.remove(self.num1_list[l - 1])
            self.sv.set(self.pms1 + self.num1_list + self.operat + self.pms2 + self.num2_list)
        elif self.num1_list == [] and self.pms1 != []:
            self.pms1 = []
            self.sv.set(self.pms1 + self.num1_list + self.operat + self.pms2 + self.num2_list)
        else:
            pass

    def num_pro(self, n):
        if n == self.num1:
            if self.pms1 != []:
                self.num1 = self.pms1[0]
            else:
                self.num1 = ''
            for i in self.num1_list:
                self.num1 += i
            if '.' in self.num1_list:
                self.num1 = float(self.num1)
            else:
                self.num1 = int(self.num1)
        else:
            if self.pms2 != []:
                self.num2 = self.pms2[0]
            else:
                self.num2 = ''
            for i in self.num2_list:
                self.num2 += i
            if '.' in self.num2_list:
                self.num2 = float(self.num2)
            else:
                self.num2 = int(self.num2)

    def result(self):

        if self.num2_list == [] or self.num2_list == ['.']:
            pass

        else:
            self.num_pro(self.num1)
            self.num_pro(self.num2)
            if self.operat == ['+']:
                r = self.num1 + self.num2
                self.data_empty()
                self.num1_list = list(str(r))
                self.sv.set(self.pms1 + self.num1_list + self.operat + self.pms2 + self.num2_list)

            elif self.operat == ['-']:
                r = self.num1 - self.num2
                self.data_empty()
                self.num1_list = list(str(r))
                self.sv.set(self.pms1 + self.num1_list + self.operat + self.pms2 + self.num2_list)

            elif self.operat == ['x']:
                r = self.num1 * self.num2
                self.data_empty()
                self.num1_list = list(str(r))
                self.sv.set(self.pms1 + self.num1_list + self.operat + self.pms2 + self.num2_list)

            elif self.operat == ['÷']:
                try:
                    r = self.num1 / self.num2
                    self.data_empty()
                    self.num1_list = list(str(r))
                    self.sv.set(self.pms1 + self.num1_list + self.operat + self.pms2 + self.num2_list)
                except ZeroDivisionError:
                    self.sv.set('除数不能为0')
                except Exception:
                    pass

    def close(self):
        tk.destroy()

if __name__ == '__main__':
    cc = calculator()

 

转载于:https://www.cnblogs.com/lzybb/p/10498051.html

你可能感兴趣的:(自学python-tkinter-计算器)