Python小试牛刀:GUI(图形界面)实现计算器UI界面(三)

上一篇:Python小试牛刀:GUI(图形界面)实现计算器UI界面(二)-CSDN博客

回顾前两篇文章,第一篇文章主要实现了计算器UI界面如何布局,以及简单概述Python常用的GUI库。第二篇文章主要实现了计算器UI界面按钮组件与事件的交互,而在本片文章则是实现计算器完整功能。

运行结果:

代码设计

"""计算器
"""# 通配符'*'
__all__ = ['main']# 计算器UI设计
class CalculatorUI:import tkinter as tkfrom tkinter import fontbase = tk.Tk()              # 新建窗口base.title('计算器')         # 设置标题base.geometry("458x400")    # 设置窗口像素大小# 全局变量labelData1 = tk.StringVar()  # 标签数据labelData2 = tk.StringVar()  # 标签数据# 设置字体样式setChineseFont = font.Font(family='Arial', size=20, weight='bold')setFont = font.Font(family='Helvetica', size=12, weight='bold')# 主框架mainFrame = tk.LabelFrame(base, text='标准', borderwidth=2, relief=tk.FLAT, font=setChineseFont)mainFrame.pack(expand=True)# 标签框架labelFrame = tk.Frame(mainFrame, borderwidth=2, relief=tk.GROOVE)labelFrame.grid(columnspan=4)# 标签showLabel1 = tk.Label(labelFrame, textvariable=labelData1, anchor='e', width=26, font=setChineseFont)showLabel1.pack()showLabel2 = tk.Label(labelFrame, textvariable=labelData2, anchor='e', width=26, font=setChineseFont)showLabel2.pack()# 删除按钮clear = tk.Button(mainFrame, text='C', width=10, height=2, font=setFont)clear.grid(row=1, column=0)# 退格按钮backSpace = tk.Button(mainFrame, text='⬅', width=10, height=2, font=setFont)backSpace.grid(row=1, column=1)# 余数(百分号)remainder = tk.Button(mainFrame, text='%', width=10, height=2, font=setFont)remainder.grid(row=1, column=2)# 除号division = tk.Button(mainFrame, text='➗', width=10, height=2, font=setFont)division.grid(row=1, column=3)# 7seven = tk.Button(mainFrame, text='7', width=10, height=2, font=setFont)seven.grid(row=2, column=0)# 8eight = tk.Button(mainFrame, text='8', width=10, height=2, font=setFont)eight.grid(row=2, column=1)# 9nine = tk.Button(mainFrame, text='9', width=10, height=2, font=setFont)nine.grid(row=2, column=2)# 乘号multiplication = tk.Button(mainFrame, text='✖', width=10, height=2, font=setFont)multiplication.grid(row=2, column=3)# 4four = tk.Button(mainFrame, text='4', width=10, height=2, font=setFont)four.grid(row=3, column=0)# 5five = tk.Button(mainFrame, text='5', width=10, height=2, font=setFont)five.grid(row=3, column=1)# 6six = tk.Button(mainFrame, text='6', width=10, height=2, font=setFont)six.grid(row=3, column=2)# 减法subtraction = tk.Button(mainFrame, text='➖', width=10, height=2, font=setFont)subtraction.grid(row=3, column=3)# 1one = tk.Button(mainFrame, text='1', width=10, height=2, font=setFont)one.grid(row=4, column=0)# 2two = tk.Button(mainFrame, text='2', width=10, height=2, font=setFont)two.grid(row=4, column=1)# 3three = tk.Button(mainFrame, text='3', width=10, height=2, font=setFont)three.grid(row=4, column=2)# 加法addition = tk.Button(mainFrame, text='➕', width=10, height=2, font=setFont)addition.grid(row=4, column=3)# 括号brackets = tk.Button(mainFrame, text='(  )', width=10, height=2, font=setFont)brackets.grid(row=5, column=0)# 0zero = tk.Button(mainFrame, text='0', width=10, height=2, font=setFont)zero.grid(row=5, column=1)# 小数点.dit = tk.Button(mainFrame, text='.', width=10, height=2, font=setFont)dit.grid(row=5, column=2)# 等于equal = tk.Button(mainFrame, text='=', width=10, height=2, background='#00BFFF', font=setFont)equal.grid(row=5, column=3)# 按钮间距tk.Label(mainFrame, height=3, width=1).grid(row=1, column=4)  # 行填充tk.Label(mainFrame, height=3, width=1).grid(row=2, column=4)tk.Label(mainFrame, height=3, width=1).grid(row=3, column=4)tk.Label(mainFrame, height=3, width=1).grid(row=4, column=4)tk.Label(mainFrame, height=3, width=1).grid(row=5, column=4)tk.Label(mainFrame, height=1, width=16).grid(row=6, column=1)  # 列填充tk.Label(mainFrame, height=1, width=16).grid(row=6, column=3)# 初始化事件
def initUI(event):# 0-9UI.zero.config(background='#f0f0f0')        # 0UI.one.config(background='#f0f0f0')         # 1UI.two.config(background='#f0f0f0')         # 2UI.three.config(background='#f0f0f0')       # 3UI.four.config(background='#f0f0f0')        # 4UI.five.config(background='#f0f0f0')        # 5UI.six.config(background='#f0f0f0')         # 6UI.seven.config(background='#f0f0f0')       # 7UI.eight.config(background='#f0f0f0')       # 8UI.nine.config(background='#f0f0f0')        # 9# 特殊字符UI.clear.config(background='#f0f0f0')       # 删除UI.backSpace.config(background='#f0f0f0')   # 退格UI.remainder.config(background='#f0f0f0')   # 百分号/求余UI.division.config(background='#f0f0f0')    # 除号UI.multiplication.config(background='#f0f0f0')  # 乘号UI.subtraction.config(background='#f0f0f0')     # 减号UI.addition.config(background='#f0f0f0')        # 加号UI.equal.config(background='#00BFFF')           # 等于UI.brackets.config(background='#f0f0f0')        # 括号UI.dit.config(background='#f0f0f0')             # 小数点# 鼠标在组件上的焦点事件
# 0-9
# 0
def zeroBackground(event):UI.zero.config(background='pink')
def zeroReleaseBackground(event):UI.zero.config(state=tk.DISABLED, background='pink')UI.base.update()time.sleep(0.1)UI.zero.config(state=tk.NORMAL, background='#f0f0f0')zeroEvent(event)
# 1
def oneBackground(event):UI.one.config(background='pink')
def oneReleaseBackground(event):UI.one.config(state=tk.DISABLED, background='pink')UI.base.update()time.sleep(0.1)UI.one.config(state=tk.NORMAL, background='#f0f0f0')oneEvent(event)
# 2
def twoBackground(event):UI.two.config(background='pink')
def twoReleaseBackground(event):UI.two.config(state=tk.DISABLED, background='pink')UI.base.update()time.sleep(0.1)UI.two.config(state=tk.NORMAL, background='#f0f0f0')twoEvent(event)
# 3
def threeBackground(event):UI.three.config(background='pink')
def threeReleaseBackground(event):UI.three.config(state=tk.DISABLED, background='pink')UI.base.update()time.sleep(0.1)UI.three.config(state=tk.NORMAL, background='#f0f0f0')threeEvent(event)
# 4
def fourBackground(event):UI.four.config(background='pink')
def fourReleaseBackground(event):UI.four.config(state=tk.DISABLED, background='pink')UI.base.update()time.sleep(0.1)UI.four.config(state=tk.NORMAL, background='#f0f0f0')fourEvent(event)
# 5
def fiveBackground(event):UI.five.config(background='pink')
def fiveReleaseBackground(event):UI.five.config(state=tk.DISABLED, background='pink')UI.base.update()time.sleep(0.1)UI.five.config(state=tk.NORMAL, background='#f0f0f0')fiveEvent(event)
# 6
def sixBackground(event):UI.six.config(background='pink')
def sixReleaseBackground(event):UI.six.config(state=tk.DISABLED, background='pink')UI.base.update()time.sleep(0.1)UI.six.config(state=tk.NORMAL, background='#f0f0f0')sixEvent(event)
# 7
def sevenBackground(event):UI.seven.config(background='pink')
def sevenReleaseBackground(event):UI.seven.config(state=tk.DISABLED, background='pink')UI.base.update()time.sleep(0.1)UI.seven.config(state=tk.NORMAL, background='#f0f0f0')sevenEvent(event)
# 8
def eightBackground(event):UI.eight.config(background='pink')
def eightReleaseBackground(event):UI.eight.config(state=tk.DISABLED, background='pink')UI.base.update()time.sleep(0.1)UI.eight.config(state=tk.NORMAL, background='#f0f0f0')eightEvent(event)
# 9
def nineBackground(event):UI.nine.config(background='pink')
def nineReleaseBackground(event):UI.nine.config(state=tk.DISABLED, background='pink')UI.base.update()time.sleep(0.1)UI.nine.config(state=tk.NORMAL, background='#f0f0f0')nineEvent(event)# 特殊字符
# 删除
def clearBackground(event):UI.clear.config(background='pink')
def clearReleaseBackground(event):UI.clear.config(state=tk.DISABLED, background='pink')UI.base.update()time.sleep(0.1)UI.clear.config(state=tk.NORMAL, background='#f0f0f0')clearEvent(event)
# 退格
def backSpaceBackground(event):UI.backSpace.config(background='pink')
def backSpaceReleaseBackground(event):UI.backSpace.config(state=tk.DISABLED, background='pink')UI.base.update()time.sleep(0.1)UI.backSpace.config(state=tk.NORMAL, background='#f0f0f0')backSpaceEvent(event)
# 百分号/求余
def remainderBackground(event):UI.remainder.config(background='pink')
def remainderReleaseBackground(event):UI.remainder.config(state=tk.DISABLED, background='pink')UI.base.update()time.sleep(0.1)UI.remainder.config(state=tk.NORMAL, background='#f0f0f0')remainderEvent(event)
# 除号
def divisionBackground(event):UI.division.config(background='pink')
def divisionReleaseBackground(event):UI.division.config(state=tk.DISABLED, background='pink')UI.base.update()time.sleep(0.1)UI.division.config(state=tk.NORMAL, background='#f0f0f0')divisionEvent(event)
# 乘号
def multiplicationBackground(event):UI.multiplication.config(background='pink')
def multiplicationReleaseBackground(event):UI.multiplication.config(state=tk.DISABLED, background='pink')UI.base.update()time.sleep(0.1)UI.multiplication.config(state=tk.NORMAL, background='#f0f0f0')multiplicationEvent(event)
# 减号
def subtractionBackground(event):UI.subtraction.config(background='pink')
def subtractionReleaseBackground(event):UI.subtraction.config(state=tk.DISABLED, background='pink')UI.base.update()time.sleep(0.1)UI.subtraction.config(state=tk.NORMAL, background='#f0f0f0')subtractionEvent(event)
# 加号
def additionBackground(event):UI.addition.config(background='pink')
def additionReleaseBackground(event):UI.addition.config(state=tk.DISABLED, background='pink')UI.base.update()time.sleep(0.1)UI.addition.config(state=tk.NORMAL, background='#f0f0f0')additionEvent(event)
# 等于
def equalBackground(event):UI.equal.config(background='pink')
def equalReleaseBackground(event):UI.equal.config(state=tk.DISABLED, background='pink')UI.base.update()time.sleep(0.1)UI.equal.config(state=tk.NORMAL, background='#00BFFF')equalEvent(event)
# 括号
def bracketsBackground(event):UI.brackets.config(background='pink')
def bracketsReleaseBackground(event):UI.brackets.config(state=tk.DISABLED, background='pink')UI.base.update()time.sleep(0.1)UI.brackets.config(state=tk.NORMAL, background='#f0f0f0')bracketsEvent(event)
# 小数点
def ditBackground(event):UI.dit.config(background='pink')
def ditReleaseBackground(event):UI.dit.config(state=tk.DISABLED, background='pink')UI.base.update()time.sleep(0.1)UI.dit.config(state=tk.NORMAL, background='#f0f0f0')ditEvent(event)# 组件背景颜色事件触发
def widgetColor():# 初始化UI.base.bind('<Leave>', initUI)UI.showLabel1.config(foreground='gray', background='white')UI.showLabel2.config(background='white')# 0-9UI.zero.bind('<Motion>', zeroBackground)        # 0UI.one.bind('<Motion>', oneBackground)          # 1UI.two.bind('<Motion>', twoBackground)          # 2UI.three.bind('<Motion>', threeBackground)      # 3UI.four.bind('<Motion>', fourBackground)        # 4UI.five.bind('<Motion>', fiveBackground)        # 5UI.six.bind('<Motion>', sixBackground)          # 6UI.seven.bind('<Motion>', sevenBackground)      # 7UI.eight.bind('<Motion>', eightBackground)      # 8UI.nine.bind('<Motion>', nineBackground)        # 9# 特殊字符UI.clear.bind('<Motion>', clearBackground)                      # 删除UI.backSpace.bind('<Motion>', backSpaceBackground)              # 退格UI.remainder.bind('<Motion>', remainderBackground)              # 百分号/求余UI.division.bind('<Motion>', divisionBackground)                # 除号UI.multiplication.bind('<Motion>', multiplicationBackground)    # 乘号UI.subtraction.bind('<Motion>', subtractionBackground)          # 减号UI.addition.bind('<Motion>', additionBackground)                # 加号UI.equal.bind('<Motion>', equalBackground)                      # 等于UI.brackets.bind('<Motion>', bracketsBackground)                # 括号UI.dit.bind('<Motion>', ditBackground)                          # 小数点# 按钮按下UI.base.bind('<KeyPress-0>', zeroReleaseBackground)     # 0UI.zero.bind('<Button-1>', zeroEvent)UI.base.bind('<KeyPress-1>', oneReleaseBackground)      # 1UI.one.bind('<Button-1>', oneEvent)UI.base.bind('<KeyPress-2>', twoReleaseBackground)      # 2UI.two.bind('<Button-1>', twoEvent)UI.base.bind('<KeyPress-3>', threeReleaseBackground)    # 3UI.three.bind('<Button-1>', threeEvent)UI.base.bind('<KeyPress-4>', fourReleaseBackground)     # 4UI.four.bind('<Button-1>', fourEvent)UI.base.bind('<KeyPress-5>', fiveReleaseBackground)     # 5UI.five.bind('<Button-1>', fiveEvent)UI.base.bind('<KeyPress-6>', sixReleaseBackground)      # 6UI.six.bind('<Button-1>', sixEvent)UI.base.bind('<KeyPress-7>', sevenReleaseBackground)    # 7UI.seven.bind('<Button-1>', sevenEvent)UI.base.bind('<KeyPress-8>', eightReleaseBackground)    # 8UI.eight.bind('<Button-1>', eightEvent)UI.base.bind('<KeyPress-9>', nineReleaseBackground)     # 9UI.nine.bind('<Button-1>', nineEvent)UI.base.bind('<KeyPress-Delete>', clearReleaseBackground)    # 删除UI.base.bind('<KeyPress-c>', clearReleaseBackground)         # 删除UI.base.bind('<Key-C>', clearReleaseBackground)              # 删除UI.clear.bind('<Button-1>', clearEvent)UI.base.bind('<KeyPress-BackSpace>', backSpaceReleaseBackground)  # 退格UI.backSpace.bind('<Button-1>', backSpaceEvent)UI.base.bind('<Shift-Key-%>', remainderReleaseBackground)         # 百分号、求余UI.remainder.bind('<Button-1>', remainderEvent)UI.base.bind('<KeyPress-slash>', divisionReleaseBackground)       # 除号UI.division.bind('<Button-1>', divisionEvent)UI.base.bind('<KeyPress-asterisk>', multiplicationReleaseBackground)    # 乘号UI.base.bind('<Shift-Key-*>', multiplicationReleaseBackground)          # 乘号UI.multiplication.bind('<Button-1>', multiplicationEvent)UI.base.bind('<KeyPress-minus>', subtractionReleaseBackground)          # 减号UI.subtraction.bind('<Button-1>', subtractionEvent)UI.base.bind('<KeyPress-plus>', additionReleaseBackground)              # 加号UI.base.bind('<Shift-Key-+>', additionReleaseBackground)                # 加号UI.addition.bind('<Button-1>', additionEvent)UI.base.bind('<KeyPress-Return>', equalReleaseBackground)               # 等号UI.base.bind('<KeyPress-equal>', equalReleaseBackground)                # 等号UI.equal.bind('<Button-1>', equalEvent)UI.base.bind('<Shift-Key-(>', bracketsReleaseBackground)                # 左括号UI.base.bind('<Shift-Key-)>', bracketsReleaseBackground)                # 右括号UI.brackets.bind('<Button-1>', bracketsEvent)UI.base.bind('<KeyPress-period>', ditReleaseBackground)                 # 小数点UI.dit.bind('<Button-1>', ditEvent)# 0 事件
def zeroEvent(event):global labelShow2# 数字前面不能是右括号')'if ('原来是小瘪三'+labelShow2)[-1] in ')=':returnlabelShow2 += '0'# 补小数点if labelShow2 == '0' or labelShow2[-2] in '(+-×÷':labelShow2 += '.'UI.labelData2.set(labelShow2)UI.zero.config(activeforeground='gray')# 1 事件
def oneEvent(event):global labelShow2# 数字前面不能是右括号')'if ('防止空字符'+labelShow2)[-1] in ')=':returnlabelShow2 += '1'UI.labelData2.set(labelShow2)UI.one.config(activeforeground='gray')# 2 事件
def twoEvent(event):global labelShow2# 数字前面不能是右括号')'if ('什么字符都可以'+labelShow2)[-1] in ')=':returnlabelShow2 += '2'UI.labelData2.set(labelShow2)UI.two.config(activeforeground='gray')# 3 事件
def threeEvent(event):global labelShow2# 数字前面不能是右括号')'if ('不影响代码'+labelShow2)[-1] in ')=':returnlabelShow2 += '3'UI.labelData2.set(labelShow2)UI.three.config(activeforeground='gray')# 4 事件
def fourEvent(event):global labelShow2# 数字前面不能是右括号')'if ('虽然可以封装成函数'+labelShow2)[-1] in ')=':returnlabelShow2 += '4'UI.labelData2.set(labelShow2)UI.four.config(activeforeground='gray')# 5 事件
def fiveEvent(event):global labelShow2# 数字前面不能是右括号')'if ('但是只有两行代码'+labelShow2)[-1] in ')=':returnlabelShow2 += '5'UI.labelData2.set(labelShow2)UI.five.config(activeforeground='gray')# 6 事件
def sixEvent(event):global labelShow2# 数字前面不能是右括号')'if ('调用函数还是两行代码'+labelShow2)[-1] in ')=':returnlabelShow2 += '6'UI.labelData2.set(labelShow2)UI.six.config(activeforeground='gray')# 7 事件
def sevenEvent(event):global labelShow2# 数字前面不能是右括号')'if ('索性来个自我介绍吧'+labelShow2)[-1] in ')=':returnlabelShow2 += '7'UI.labelData2.set(labelShow2)UI.seven.config(activeforeground='gray')# 8 事件
def eightEvent(event):global labelShow2# 数字前面不能是右括号')'if ('我是周华2022'+labelShow2)[-1] in ')=':returnlabelShow2 += '8'UI.labelData2.set(labelShow2)UI.eight.config(activeforeground='gray')# 9 事件
def nineEvent(event):global labelShow2# 数字前面不能是右括号')'if ('欢迎大家关注!'+labelShow2)[-1] in ')=':returnlabelShow2 += '9'UI.labelData2.set(labelShow2)UI.nine.config(activeforeground='gray')# 删除 事件
def clearEvent(event):global labelShow2, operator, operationData, bracketsFlag# 数据初始化bracketsFlag = 0labelShow2 = ''operator = []operationData = []UI.labelData2.set(labelShow2)UI.clear.config(activeforeground='gray')# 退格 事件
def backSpaceEvent(event):global labelShow2# 在数据内退格if not operator:labelShow2 = labelShow2[:-1:]# 运算符退格elif operator and operationData:if labelShow2[-1] in '+-×÷%':operator.pop()operationData.pop()labelShow2 = labelShow2[:-1:]UI.labelData2.set(labelShow2)UI.backSpace.config(activeforeground='gray')# 求余 事件
def remainderEvent(event):global labelShow2# 首个字符不能出现百分号/求余if not labelShow2:return# 百分号前面不能出现运算符,除了右括号')'elif labelShow2[-1] in '+-×÷%(.=':return# 分割数据,获取数值和运算符elif not operator:operationData.append(labelShow2)elif operator:operationData.append(labelShow2.split(operationData[-1] + operator[-1])[-1])operator.append('%')labelShow2 += '%'print(operator, operationData)UI.labelData2.set(labelShow2)UI.remainder.config(activeforeground='gray')# 除法 事件
def divisionEvent(event):global labelShow2# 首个字符不能出现除号if not labelShow2:return# 除号前面不能出现运算符,除了右括号')'和百分号'%'elif labelShow2[-1] in '+-×÷(.=':return# 分割数据,获取数值和运算符elif not operator:operationData.append(labelShow2)elif operator:if labelShow2[-1] == '%':operationData[-1] += operator.pop()else:operationData.append(labelShow2.split(operationData[-1]+operator[-1])[-1])operator.append('÷')labelShow2 += '÷'print(operator, operationData)UI.labelData2.set(labelShow2)UI.division.config(activeforeground='gray')# 乘法 事件
def multiplicationEvent(event):global labelShow2# 首个字符不能出现乘号if not labelShow2:return# 乘号前面不能出现运算符,除了右括号')'和百分号'%'elif labelShow2[-1] in '+-×÷(.=':return# 分割数据,获取数值和运算符elif not operator:operationData.append(labelShow2)elif operator:if labelShow2[-1] == '%':operationData[-1] += operator.pop()else:operationData.append(labelShow2.split(operationData[-1] + operator[-1])[-1])operator.append('×')labelShow2 += '×'print(operator, operationData)UI.labelData2.set(labelShow2)UI.multiplication.config(activeforeground='gray')# 减法 事件
def subtractionEvent(event):addFlag = 1  # 添加运算符旗帜global labelShow2# 首字符出现减号,视为负号if not labelShow2:addFlag = 0  # 添加运算符旗帜# 减号前面不能出现运算符,除了括号'()'和百分号'%'elif labelShow2[-1] in '+-×÷.=':return# 分割数据,获取数值和运算符elif not operator and labelShow2[-1] not in '(':operationData.append(labelShow2)# 非首个数据elif operator and operationData:if labelShow2[-1] == '%':operationData[-1] += operator.pop()elif labelShow2[-1] == '(':addFlag = 0  # 添加运算符旗帜else:operationData.append(labelShow2.split(operationData[-1] + operator[-1])[-1])else:addFlag = 0# 不保存运算符旗帜if addFlag:operator.append('-')print(operator, operationData)labelShow2 += '-'UI.labelData2.set(labelShow2)UI.subtraction.config(activeforeground='gray')# 加法 事件
def additionEvent(event):addFlag = 1  # 添加运算符旗帜global labelShow2# 首字符出现加号,视为正号if not labelShow2:addFlag = 0  # 添加运算符旗帜# 加号前面不能出现运算符,除了括号'()'和百分号'%'elif labelShow2[-1] in '+-×÷.=':return# 分割数据,获取数值和运算符elif not operator and labelShow2[-1] not in '(':operationData.append(labelShow2)# 非首个数据elif operator and operationData:if labelShow2[-1] == '%':operationData[-1] += operator.pop()elif labelShow2[-1] == '(':addFlag = 0  # 添加运算符旗帜else:operationData.append(labelShow2.split(operationData[-1] + operator[-1])[-1])else:addFlag = 0# 不保存运算符旗帜if addFlag:operator.append('+')print(operator, operationData)labelShow2 += '+'  # 添加加号UI.labelData2.set(labelShow2)UI.addition.config(activeforeground='gray')# 等于 事件
def equalEvent(event):global labelShow2, labelShow1labelShow1 = labelShow2     # 显示式子# 首字符不能输入等号if not labelShow2:return# 等号前不能出现的运算符,除了数字、右括号、百分号elif labelShow2[-1] in '+-×÷=.':return# 括号必须成对,elif len(re.findall(r'\(', labelShow2)) != len(re.findall(r'\)', labelShow2)):UI.labelData1.set(labelShow1+'=错误')UI.labelData2.set('括号不完整')return# 等号前面不能是不带括号的正数elif not operator and labelShow2[0] != '+' and not len(re.findall(r'\(', labelShow2)):return# 处理等号前面只有一个数时elif not operator or (labelShow2.strip('()+-')[-1] == '%' and len(operator) == 1 and operator[0] == '%'):subtractionNum = len(re.findall('-', labelShow2))   # 减号数# 查找百分号if labelShow2.strip('()+-')[-1] == '%':num = float(labelShow2.strip('()+-%')) / 100# 奇数负为负,偶数负为正if subtractionNum % 2:labelShow2 = str(-num)else:labelShow2 = str(num)elif labelShow2.strip('()+-')[-1] != '%':num = labelShow2.strip('()+-')# 奇数负为负,偶数负为正if subtractionNum % 2:labelShow2 = '-'+numelse:labelShow2 = num# 复杂运算else:# 防止报错try:# 计算式子结果if resultEvent(event) == '求余错误':returnexcept:UI.labelData1.set(labelShow1 + '=崩溃')UI.labelData2.set('抱歉,小算脑子烧坏了')returnprint(operator, operationData)labelShow1 += '='+labelShow2        # 显示计算的式子UI.labelData1.set(labelShow1)UI.labelData2.set(labelShow2)UI.equal.config(activeforeground='gray')# 显示结果后删除存储的数据if operationData:operator.clear()operationData.clear()# 括号 事件
def bracketsEvent(event):global labelShow2, bracketsFlag# 首字符出现左括号'('if not labelShow2:labelShow2 += '('# 左括号前面不能出现数字和小数点elif labelShow2[-1] in '+-×÷(%':labelShow2 += '('# 右括号前面必须是数字和右括号elif labelShow2[-1] not in '+-×÷%(.=' and len(re.findall(r'\(', labelShow2)) != len(re.findall(r'\)', labelShow2)):labelShow2 += ')'# 括号前面的百分号if ('出来单挑啊'+labelShow2)[-2] == '%':bracketsFlag += 1if bracketsFlag % 2:labelShow2 = labelShow2[:-1:]+'('else:labelShow2 = labelShow2[:-1:]+')'UI.labelData2.set(labelShow2)UI.brackets.config(activeforeground='gray')# 小数点 事件
def ditEvent(event):global labelShow2# 小数点开头或者小数点前面是运算符就补零if not labelShow2 or labelShow2[-1] in '(+-×÷%':labelShow2 += '0'# 小数点前面不能是右括号')'elif labelShow2[-1] in ')=':return# 限制小数点输入(一)elif not operator:if len(re.findall(r'\.', labelShow2)) >= 1:return# 限制小数点输入(二)elif operator and operationData:str = labelShow2.split(operationData[-1]+operator[-1])[-1]if len(re.findall(r'\.', str)) >= 1:returnlabelShow2 += '.'UI.labelData2.set(labelShow2)UI.dit.config(activeforeground='gray')# 计算式子结果
def resultEvent(event):global labelShow1, labelShow2, operator, operationData# 分割最后一个数if labelShow2[-1] == '%':operationData[-1] += operator.pop()else:operationData.append(labelShow2.split(operationData[-1] + operator[-1])[-1])print(operator, operationData)# 化繁为简,逐个括号化简while True:leftBrackets = []       # 左括号rightBrackets = []      # 右括号minBrackets = []        # 最小括号区间# 查找括号,并存储其索引号for i in range(len(operationData)):if '(' in operationData[i]:leftBrackets.append(i)elif ')' in operationData[i]:rightBrackets.append(i)# 判断式子是否有括号if leftBrackets:sign = ''if operationData[leftBrackets[0]][0] == '-':sign = '-'# 找到最里层的括号for i in range(len(rightBrackets)):# 找到了if leftBrackets[-1] < rightBrackets[i]:left = leftBrackets[-1]right = rightBrackets[i]minBrackets.extend([left, right])break# 无括号式子设置if not minBrackets:minBrackets.extend([0, len(operationData)-1])bracketsNum = operationData[minBrackets[0]:minBrackets[1] + 1:]bracketsOperation = operator[minBrackets[0]:minBrackets[1]:]# 左括号数分割bracketsSplit = ''if re.findall(r'\(', bracketsNum[0]):bracketsSplit = bracketsNum[0].split('(')bracketsNum[0] = bracketsSplit[-1]# 化简括号内的式子while True:# 结束循环条件if not bracketsOperation:break# 排除运算错误(除数不为零、求余需整数)for i in range(len(bracketsOperation)):# 让百分号'%'参与运算for j in range(2):if '%' in bracketsNum[i+j]:bracketsNum[i+j] = str(float(bracketsNum[i+j].strip(')')[:-1:])/100)# 查找除号if bracketsOperation[i] == '÷':# 判断除数是否为零if float(bracketsNum[i+1].strip(')')) == 0:UI.labelData1.set(labelShow1 + '=错误')UI.labelData2.set('除数不能为零')return '除数错误'# 查找求余号elif bracketsOperation[i] == '%':# 判断两个数是否为整数for j in range(2):if re.findall(r'\.', bracketsNum[i+j]):UI.labelData1.set(labelShow1 + '=错误')UI.labelData2.set('求余必须为整数')return '求余错误'# 查找乘除求余(优先级高)if bracketsOperation[i] in '×÷%':# 计算两数之积if bracketsOperation[i] == '×':result = float(bracketsNum[i]) * float(bracketsNum[i+1].strip(')'))# 计算两数之商elif bracketsOperation[i] == '÷':result = float(bracketsNum[i]) / float(bracketsNum[i+1].strip(')'))# 计算两数之余elif bracketsOperation[i] == '%':result = float(bracketsNum[i]) % float(bracketsNum[i+1].strip(')'))# 修改括号区间的数据,并进入下一次循环查找bracketsNum.pop(i)bracketsNum.pop(i)bracketsOperation.pop(i)bracketsNum.insert(i, str(result))break# 查找加减(优先级低)elif bracketsOperation[i] in '+-':if '×' in bracketsOperation:continueelif '÷' in bracketsOperation:continueelif '%' in bracketsOperation:continue# 计算两数之和if bracketsOperation[i] == '+':result = float(bracketsNum[i]) + float(bracketsNum[i + 1].strip(')'))# 计算两数之差elif bracketsOperation[i] == '-':result = float(bracketsNum[i]) - float(bracketsNum[i + 1].strip(')'))# 修改括号区间的数据,并进入下一次循环查找bracketsNum.pop(i)bracketsNum.pop(i)bracketsOperation.pop(i)bracketsNum.insert(i, str(result))break# 替换数据之前要补括号leftBracketsNum = len(re.findall(r'\(', operationData[minBrackets[0]]))-1rightBracketsNum = len(re.findall(r'\)', operationData[minBrackets[1]]))-1# 删除数据for i in range(minBrackets[0], minBrackets[1]+1):operationData.pop(minBrackets[0])for i in range(minBrackets[0], minBrackets[1]):operator.pop(minBrackets[0])# 化简一个括号后,根据左括号前正负号改变数值正负号if leftBracketsNum >= 0 and bracketsSplit[-2] == '-':if bracketsNum[0][0] == '-':bracketsNum[0] = bracketsNum[0][1::]else:bracketsNum[0] = '-' + bracketsNum[0]# 合并分割的左括号leftBracketsStr = ''if leftBracketsNum > rightBracketsNum:for i in range(len(bracketsSplit)-2):leftBracketsStr += bracketsSplit[i]+'('bracketsNum[0] = leftBracketsStr + bracketsNum[0]# 补左括号,并插入计算结果数据if leftBracketsNum > rightBracketsNum:operationData.insert(minBrackets[0], f"{bracketsNum[0]}")# 补右括号,并插入计算结果数据elif rightBracketsNum > leftBracketsNum:operationData.insert(minBrackets[0], f"{bracketsNum[0]}{')' * (rightBracketsNum-leftBracketsNum)}")# 删除两边多余的括号,并插入计算结果数据elif leftBracketsNum == rightBracketsNum:string = bracketsNum[0]# 计算左括号的负号数num = 0for i in bracketsSplit[:-2:]:if i == '-':num += 1# 消除括号if leftBracketsNum >= 0 and num:if num % 2:if string[0] == '+':string = '-' + string[1::]elif string[0] != '-':string = '-' + stringelse:if string[0] == '+':string = string[1::]operationData.insert(minBrackets[0], string)# 结束条件循环条件if not operator:labelShow2 = operationData[0]if ('one piece'+operationData[0])[-2::] == '.0':labelShow2 = operationData[0][:-2:]return# 全局变量
import tkinter as tk
import time, re
UI = CalculatorUI()     # 计算器UI设计
operator = []           # 运算符
operationData = []      # 运算数据
labelShow1 = ''         # 标签内容1
labelShow2 = ''         # 标签内容2
bracketsFlag = 0        # 计数旗帜# 主函数
def main():widgetColor()       # 组件背景颜色改变UI.base.mainloop()  # 保持窗口运行# 代码测试
if __name__ == '__main__':main()
else:print(f'导入{__name__}模块')

作者:周华

创作日期:2023/11/5

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/132422.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

<Vue>使用依赖注入的方式共享数据

什么是vue依赖注入&#xff1f; Vue是一个用于构建用户界面的渐进式框架。 它提供了一种简单而灵活的方式来管理组件之间的数据流&#xff0c;即依赖注入&#xff08;Dependency Injection&#xff0c;DI&#xff09;。 依赖注入是一种设计模式&#xff0c;它允许一个组件从另一…

腾讯云CVM服务器标准型S5、SA3、S6详细介绍

腾讯云CVM服务器标准型实例的各项性能参数平衡&#xff0c;标准型云服务器适用于大多数常规业务&#xff0c;例如&#xff1a;web网站及中间件等&#xff0c;常见的标准型云服务器有CVM标准型S5、S6、SA3、SR1、S5se等规格&#xff0c;腾讯云服务器网txyfwq.com来详细说下云服务…

Synchronized与锁升级

一&#xff1a;java对象内存布局 对象在堆内存的存储布局可以划分为三个部分&#xff1a;对象头&#xff08;Header&#xff09;、实例数据&#xff08;Instance Data&#xff09; 和对齐填充 二&#xff1a;对象在堆内存中的存储布局 1&#xff1a;对象头 &#xff08;在64…

基础课23——设计客服机器人

根据调查数据显示&#xff0c;使用纯机器人完全替代客服的情况并不常见&#xff0c;人机结合模式的使用更为普遍。在这两种模式中&#xff0c;不满意用户的占比都非常低&#xff0c;不到1%。然而&#xff0c;在满意用户方面&#xff0c;人机结合模式的用户满意度明显高于其他模…

Redis02-持久化策略

目录 RDB&#xff08;Redis DataBase Backup file&#xff09; RDB执行原理 AOF&#xff08;Append-Only File&#xff09; RDB和AOF对比 Redis支持多种持久化方式&#xff0c;以确保数据在内存中持久存储&#xff0c;以便在Redis服务器重启时数据不会丢失。Redis中持久化的…

Android Studio(列表视图ListView)

前言 前面在适配器章节&#xff0c;已经介绍了ListView的作用(干什么的)&#xff0c;这节将主要介绍如何去设计ListView页面视图。 思考 列表视图需要些什么&#xff1f; 1. 列表项容器&#xff08;装载各列表项的容器&#xff09;&#xff1a;<ListView/> 2. 列表项布局…

MySQL数据脱敏(Data masking plugin functions)

对于企业而言&#xff0c;数据脱敏可以在数据共享或测试时用于保护敏感数据&#xff08;如信用卡&#xff0c;社保卡&#xff0c;地址等&#xff09;。通过对敏感数据进行脱敏处理&#xff0c;组织可以最大限度地降低数据泄露和未经授权访问的风险&#xff0c;同时仍能够使用真…

AI技术再刷屏!明星集体“说”外语,有何风险?

近日&#xff0c;一段美国歌手泰勒斯威夫特“说”中文的短视频在网络刷屏&#xff0c;引发热议。 视频中&#xff0c;泰勒斯威夫特“说”着流利中文&#xff0c;音色和讲母语时的音色类似&#xff0c;甚至连口型都能对上。 类似的视频还有很多外国人“说”地道中文、很多中国…

figma-如何批量修改字体

一.选择字体 二.批量替换 编辑—>替换相同字体

UI设计工具都哪些常用的,推荐这5款

对于UI设计师来说&#xff0c;日常工作无非是围绕“需求分析”→设计实施→“开发交付”这三个环节来进行。 然而&#xff0c;在每个环节中&#xff0c;设计师使用的工具却完全不同。在这里&#xff0c;我收集整理了UI设计师在日常工作中常用的五种工具&#xff0c;希望能为新…

【ChatOCR】OCR+LLM定制化关键信息抽取(附开源大语言模型汇总整理)

目录 背景技术方案存在的问题及解决思路关键信息提取结果其他解决方案替换文心一言LangChain大型多模态模型&#xff08;Large Multimodal Model, LMM&#xff09; 开源大模型汇总LLaMA —— Meta 大语言模型Stanford Alpaca —— 指令调优的 LLaMA 模型Lit-LLaMA —— 基于 na…

数据结构线性表——单链表

前言&#xff1a;小伙伴们又见面啦&#xff0c;这篇文章我们来一起学习线性表的第二模块——单链表。 单链表的学习就要开始上强度啦&#xff0c;小伙伴们一定要努力&#xff0c;坚持&#xff01; 目录 一.什么是单链表 二.单链表与顺序表的区别 三.单链表的实现 1.单链表…

ClickHouse 学习之从高级到监控以及备份(二)

第 一 部分 高级篇 第 1 章 Explain 查看执行计划 在 clickhouse 20.6 版本之前要查看 SQL 语句的执行计划需要设置日志级别为 trace 才能可以看到&#xff0c;并且只能真正执行 sql&#xff0c;在执行日志里面查看。在 20.6 版本引入了原生的执行计划的语法。在 20.6.3 版本成…

【MongoDB】集群搭建实战 | 副本集 Replica-Set | 分片集群 Shard-Cluster | 安全认证

文章目录 MongoDB 集群架构副本集主节点选举原则搭建副本集主节点从节点仲裁节点 连接节点添加副本从节点添加仲裁者节点删除节点 副本集读写操作副本集中的方法 分片集群分片集群架构目标第一个副本集第二个副本集配置集初始化副本集路由集添加分片开启分片集合分片删除分片 安…

第23期 | GPTSecurity周报

GPTSecurity是一个涵盖了前沿学术研究和实践经验分享的社区&#xff0c;集成了生成预训练 Transformer&#xff08;GPT&#xff09;、人工智能生成内容&#xff08;AIGC&#xff09;以及大型语言模型&#xff08;LLM&#xff09;等安全领域应用的知识。在这里&#xff0c;您可以…

Java 高效生成按指定间隔连续递增的列表(int,double)

简介 Java 按照指定间隔生成连续递增的List 列表&#xff08;引入Stream 类和流操作来提高效率&#xff09;&#xff1a; 1. 生成递增的List< Integer> Testpublic void test009(){int start 1;int interval 2;int count 10;List<Integer> list IntStream.ite…

【亚马逊云科技产品测评】活动征文|亚马逊云科技AWS之EC2详细测评

引言 &#xff08;授权声明&#xff1a;本篇文章授权活动官方亚马逊云科技文章转发、改写权&#xff0c;包括不限于在 Developer Centre, 知乎&#xff0c;自媒体平台&#xff0c;第三方开发者媒体等亚马逊云科技官方渠道&#xff09; 在当前的数字化时代&#xff0c;云服务已…

算法题:203. 移除链表元素(递归法、设置虚拟头节点法等3种方法)Java实现创建链表与解析链表

1、算法思路 讲一下设置虚拟头节点的那个方法&#xff0c;设置一个新节点指向原来链表的头节点&#xff0c;这样我们就可以通过判断链表的当前节点的后继节点值是不是目标删除值&#xff0c;来判断是否删除这个后继节点了。如果不设置虚拟头节点&#xff0c;则需要将头节点和后…

【SpringSecurity】简介

SpringSecurity简介 Spring Security 的前身是Acegi Security&#xff0c;在被收纳为Spring 子项目后正式更名为Spring Security。Spring Security目前已经到了6.x&#xff0c;并且加入了原生OAuth2.0框架&#xff0c;支持更加现代化的密码加密方式。可以预见&#xff0c;在Ja…

HDFS速通之一文详解HDFS全部知识点

文章目录 HDFS介绍HDFS体系HDFS的Shell介绍HDFS的常见Shell操作 HDFS案例实操Java操作HDFS配置环境 HDFS的回收站HDFS的安全模式实战&#xff1a;定时上传数据至HDFSHDFS的高可用和高扩展HDFS的高可用(HA)HDFS的高扩展(Federation) HDFS介绍 HDFS是一个分布式的文件系统 假设…