如何利用python的tkinter实现一个简单的计算器
通过学习这篇文章,我学会了如何用tkinter库制作一个简易计算器
首先一个计算器最基本的是窗口和按钮
所以可以先定义一个窗口并设置输入框的内容
equal_is = False txtchange='' #设置输入框的内容
#创建窗体 window = tk.Tk() window.geometry('250x350') window.title('简易计算器')
然后再用函数定义按钮和生成按钮
#定义空函数,在没有赋值的时候输出为text def create_button(text, col, row, cs, rs, print='', px=(1, 1), py=(1, 1)): #创建函数生成按钮 if print == '': t = text else: t = print a = tk.Button(window, text=text , width=4, command=lambda:(text_print(t))) #输入内容 a.grid(column=col, row=row, columnspan=cs, rowspan=rs, padx=px, pady=py, sticky='nswe') return (a) #定义函数自动填充行和列 def grid_rowconfigure(*rows): #函数填充行。 *rows:允许接收多个参数 for i in rows: window.grid_rowconfigure(i, weight=1) def grid_columnconfigure(*cols): #函数填充列。 *cols:允许接收多个参数 for i in cols: window.grid_columnconfigure(i, weight=1) grid_rowconfigure(2, 3, 4, 5) grid_columnconfigure(0, 1, 2, 3, 4)
上面的代码块是用来规范主窗体,下面的代码块是生成输入框和显示框和创建按钮
#生成输入框 printf=tk.Label(window, text='', bg='white', fg='black', font=('宋体',24), anchor='w', relief='flat') printf.grid(column=0, row=0, columnspan=5, rowspan=1, sticky='we') #生成显示框 displayf=tk.Label(window, bg='white', fg='grey', height=1, font=('宋体',22), anchor='w', relief='flat') displayf.grid(column=0, row=1, columnspan=5, rowspan=1, sticky='we')
#生成按钮 button = {} button['1'] = create_button('1', 0, 4, 1, 1) button['2'] = create_button('2', 1, 4, 1, 1) button['3'] = create_button('3', 2, 4, 1, 1) button['4'] = create_button('4', 0, 3, 1, 1) button['5'] = create_button('5', 1, 3, 1, 1) button['6'] = create_button('6', 2, 3, 1, 1) button['7'] = create_button('7', 0, 2, 1, 1) button['8'] = create_button('8', 1, 2, 1, 1) button['9'] = create_button('9', 2, 2, 1, 1) button['0'] = create_button('0', 0, 5, 1, 1) button['.'] = create_button('.', 1, 5, 1, 1) button['='] = create_button('=', 4, 5, 1, 1) button['+'] = create_button('+', 3, 3, 1, 1) button['-'] = create_button('-', 3, 4, 1, 1) button['*'] = create_button('×', 3, 5, 1, 1, print='*') button['/'] = create_button('÷', 4, 4, 1, 1, print='/') button['←'] = create_button('←', 4, 3, 1, 1) button['C'] = create_button('C', 2, 5, 1, 1) button['('] = create_button('(', 3, 2, 1, 1) button[')'] = create_button(')', 4, 2, 1, 1)
然后需要我们绑定键盘事件
#绑定键盘事件 def bind_print(event): #函数键盘事件输入算式 global textchange, equal_is if event.keysym != 'Return': if event.keysym == 'BackSpace': #如果按键名为backspace,那就退格 a = str(textchange)[0:-1] textchange = a elif event.keysym == 'Delete': #清空 textchange = '' else: textchange = str(textchange) + str(event.char) #输入按键内容,char不会获得Ctrl,Shift等特殊按键的文本 printf.configure(text=textchange) #显示内容 show_is() #判断是否错误 equal_is = False else: text_equal()
#绑定键盘事件 window.bind('<Key>', bind_print) #当键盘按下任意键,执行bind_print
最后就需要定义函数操作计算过程,代码如下
#定义输入和计算函数 def text_print(x): #函数按钮输入算式 global textchange,equal_is if x != '=': if x == '←': a = str(textchange)[0:-1] textchange = a #退格 elif x == 'C': textchange = '' #清空 else: textchange = str(textchange) + str(x) #输入 printf.configure(text=textchange) show_is() equal_is=False #判断格式有无错误 if x == '=': text_equal() #计算结果 #计算结果 def text_equal(event=None): #函数计算结果并显示在输入框 global textchange, equal_is #声明全局变量 if displayf['text'] != '错误' and equal_is == False: textchange = displayf['text'] #无格式错误时,计算结果 printf.configure(text=textchange) #输入框显示结果 displayf.configure(text='') #清空显示框 equal_is = True def show_is(): #显示框内容 global textchange #声明全局变量 if textchange != '': try: textshow = eval(textchange) except(SyntaxError, TypeError, NameError): displayf.configure(text='错误') #出错显示 else: displayf.configure(text=textshow) #没出错显示结果 else: displayf.configure(text='') #输入框为空就清空显示框
import tkinter as tk #定义空函数,在没有赋值的时候输出为text def create_button(text, col, row, cs, rs, print='', px=(1, 1), py=(1, 1)): #创建函数生成按钮 if print == '': t = text else: t = print a = tk.Button(window, text=text , width=4, command=lambda:(text_print(t))) #输入内容 a.grid(column=col, row=row, columnspan=cs, rowspan=rs, padx=px, pady=py, sticky='nswe') return (a) #定义函数自动填充行和列 def grid_rowconfigure(*rows): #函数填充行。 *rows:允许接收多个参数 for i in rows: window.grid_rowconfigure(i, weight=1) def grid_columnconfigure(*cols): #函数填充列。 *cols:允许接收多个参数 for i in cols: window.grid_columnconfigure(i, weight=1) #绑定键盘事件 def bind_print(event): #函数键盘事件输入算式 global textchange, equal_is if event.keysym != 'Return': if event.keysym == 'BackSpace': #如果按键名为backspace,那就退格 a = str(textchange)[0:-1] textchange = a elif event.keysym == 'Delete': #清空 textchange = '' else: textchange = str(textchange) + str(event.char) #输入按键内容,char不会获得Ctrl,Shift等特殊按键的文本 printf.configure(text=textchange) #显示内容 show_is() #判断是否错误 equal_is = False else: text_equal() #定义输入和计算函数 def text_print(x): #函数按钮输入算式 global textchange,equal_is if x != '=': if x == '←': a = str(textchange)[0:-1] textchange = a #退格 elif x == 'C': textchange = '' #清空 else: textchange = str(textchange) + str(x) #输入 printf.configure(text=textchange) show_is() equal_is=False #判断格式有无错误 if x == '=': text_equal() #计算结果 #计算结果 def text_equal(event=None): #函数计算结果并显示在输入框 global textchange, equal_is #声明全局变量 if displayf['text'] != '错误' and equal_is == False: textchange = displayf['text'] #无格式错误时,计算结果 printf.configure(text=textchange) #输入框显示结果 displayf.configure(text='') #清空显示框 equal_is = True def show_is(): #显示框内容 global textchange #声明全局变量 if textchange != '': try: textshow = eval(textchange) except(SyntaxError, TypeError, NameError): displayf.configure(text='错误') #出错显示 else: displayf.configure(text=textshow) #没出错显示结果 else: displayf.configure(text='') #输入框为空就清空显示框 #创建窗体 window = tk.Tk() window.geometry('250x350') window.title('简易计算器') #绑定键盘事件 window.bind('<Key>', bind_print) #当键盘按下任意键,执行bind_print equal_is = False txtchange='' #设置输入框的内容 #生成输入框 printf=tk.Label(window, text='', bg='white', fg='black', font=('宋体',24), anchor='w', relief='flat') printf.grid(column=0, row=0, columnspan=5, rowspan=1, sticky='we') #生成显示框 displayf=tk.Label(window, bg='white', fg='grey', height=1, font=('宋体',22), anchor='w', relief='flat') displayf.grid(column=0, row=1, columnspan=5, rowspan=1, sticky='we') #生成按钮 button = {} button['1'] = create_button('1', 0, 4, 1, 1) button['2'] = create_button('2', 1, 4, 1, 1) button['3'] = create_button('3', 2, 4, 1, 1) button['4'] = create_button('4', 0, 3, 1, 1) button['5'] = create_button('5', 1, 3, 1, 1) button['6'] = create_button('6', 2, 3, 1, 1) button['7'] = create_button('7', 0, 2, 1, 1) button['8'] = create_button('8', 1, 2, 1, 1) button['9'] = create_button('9', 2, 2, 1, 1) button['0'] = create_button('0', 0, 5, 1, 1) button['.'] = create_button('.', 1, 5, 1, 1) button['='] = create_button('=', 4, 5, 1, 1) button['+'] = create_button('+', 3, 3, 1, 1) button['-'] = create_button('-', 3, 4, 1, 1) button['*'] = create_button('×', 3, 5, 1, 1, print='*') button['/'] = create_button('÷', 4, 4, 1, 1, print='/') button['←'] = create_button('←', 4, 3, 1, 1) button['C'] = create_button('C', 2, 5, 1, 1) button['('] = create_button('(', 3, 2, 1, 1) button[')'] = create_button(')', 4, 2, 1, 1) grid_rowconfigure(2, 3, 4, 5) grid_columnconfigure(0, 1, 2, 3, 4) #进行事件循环 window.mainloop()
运行结果