python计算器功能

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

python计算器功能

分不清是月光还是路灯   2022-09-28 我要评论

今天学习到python中界面设计部分,常用的几种图形化界面库有:Jython、wxPython和tkinter。

主要介绍tkinter模块,tkinter模块(tk接口)是Python的标准tk GUI工具包的接口。tk和tkinter可以在大多数的UNIX平台下使用,同样可以应用在Windows和Macintosh系统里。Tk8.0的后续版本可以实现本地窗口风格,并良好地运行在绝大多数平台中。

下面使用tkinter设计完成计算器功能。

(1)首先呈现一下计算器初始界面:

(2)简单说明:已经实现计算器的基本功能

(3)主要代码说明:

①导入包

import tkinter
from tkinter import *
import re
import tkinter.messagebox

 ②界面布局设置

# 创建主窗口
root = Tk()
# 设置窗口大小和位置
root.title("---计算器---")
root.geometry("320x210+500+200")
# 自动刷新字符串变量,可用 set 和 get 方法进行传值和取值
contentVar = tkinter.StringVar(root,'')
# 创建单行文本框
contentEntry = tkinter.Entry(root, textvariable=contentVar)
# 设置文本框坐标及宽高
contentEntry.place(x=20, y=10, width=260, height=30)
 
# 按钮显示内容
bvalue = ['CLC', '+', '-', '//', '0', '1', '2', '√', '3', '4', '5', '*', '6', '7', '8', '.', '9', '/', '**', '=']
index = 0
# 将按钮进行 5x4 放置
for row in range(5):
    for col in range(4):
        d = bvalue[index]
        index += 1
        btnDigit = tkinter.Button(root, text=d, command=lambda x=d:onclick(x))
        btnDigit.place(x=20 + col * 70, y=50 + row * 30, width=50, height=20)
root.mainloop()

③按钮事件的响应函数(可在评论区进行交流)

# 点击事件
def onclick(btn):
    # 运算符
    operation = ('+', '-', '*', '/', '**', '//')
    # 获取文本框中的内容
    content = contentVar.get()
    # 如果已有内容是以小数点开头的,在前面加 0
    if content.startswith('.'):
        content = '0' + content  # 字符串可以直接用+来增加字符
    # 根据不同的按钮作出不同的反应
    if btn in '0123456789':
        # 按下 0-9 在 content 中追加
        content += btn
    elif btn == '.':
        # 将 content 从 +-*/ 这些字符的地方分割开来
        lastPart = re.split(r'\+|-|\*|/', content)[-1]
        if '.' in lastPart:
            # 信息提示对话框
            tkinter.messagebox.showerror('错误', '重复出现的小数点')
            return
        else:
            content += btn
    elif btn == 'CLC':
        # 清除文本框
        content = ''
    elif btn == '=':
        try:
            # 对输入的表达式求值
            content = str(eval(content))
        except:
            tkinter.messagebox.showerror('错误', '表达式有误')
            return
    elif btn in operation:
        if content.endswith(operation):
            tkinter.messagebox.showerror('错误', '不允许存在连续运算符')
            return
        content += btn
    elif btn == '√':
        # 从 . 处分割存入 n,n 是一个列表
        n = content.split('.')
        # 如果列表中所有的都是数字,就是为了检查表达式是不是正确的
        if all(map(lambda x: x.isdigit(), n)):
            content = eval(content) ** 0.5
        else:
            tkinter.messagebox.showerror('错误', '表达式错误')
            return

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们