百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

通过创建计算器来学习 Python(用python设计一个简单的计算器程序)

off999 2024-10-02 18:35 27 浏览 0 评论

本文详细介绍了如何使用 Python 和 Tkinter 库开发 Basic Calculator 应用程序。该应用程序旨在执行基本的算术运算,并提供用户友好的图形界面,以便于交互。

Python 计算器项目的先决条件

  • 了解基本的 Python 语法、函数、控制结构和错误处理。
  • 熟悉 Tkinter 库将用于创建所有 GUI 组件。
  • 确保 Python 和 Tkinter 库已正确安装在系统上。

Python 计算器项目的目标

此 Python 项目的主要目标是:

  • 目标是创建一个能够执行基本算术运算(如加法、减法、乘法和除法)的函数式计算器。
  • 提供直观且易于导航的图形用户界面 (GUI)。
  • 确保计算器有效地处理用户输入和错误。
  • 应实施平方根计算和字符删除等其他功能,以增强应用程序的可用性。

Python 计算器的分步代码说明

Basic Calculator 应用程序是使用 Python 开发的,将 Tkinter 库用于 GUI 组件,将数学库用于数学运算。该代码被结构化为处理特定任务的各种函数,确保采用模块化和有序的方法来构建应用程序。

导入库

import tkinter as tk
import math

我们首先导入 Tkinter 和 math。Tkinter 提供了创建 GUI 的必要工具,允许开发具有交互式组件的窗口化应用程序。数学库执行特定的数学运算,例如计算平方根。

函数定义

  1. 计算表达式
# Function to evaluate the expression
def calculate_expression():
    try:
        result = eval(display.get())
        display.delete(0, tk.END)
        display.insert(tk.END, str(result))
    except Exception as e:
        display.delete(0, tk.END)
        display.insert(tk.END, "Error")

calculate_expression 函数计算用户输入的数学表达式。它从显示中检索文本,并使用 eval 函数计算结果,然后将其显示在输入字段中。如果发生错误,例如语法错误或被零除,该函数将捕获异常并显示“错误”。

2. 清晰显示

# Function to clear the entry field
def clear_display():
    display.delete(0, tk.END)

clear_display 函数清除显示字段,允许用户开始新的计算。它使用显示器。Delete 方法从输入字段中删除任何文本。

3. 删除最后一个字符

# Function to delete the last character from the entry field
def delete_last_character():
    current_text = display.get()
    if current_text:
        display.delete(len(current_text) - 1, tk.END)

此功能允许用户通过删除在显示字段中输入的最后一个字符来纠正错误。它首先检索当前文本,然后删除最后一个字符(如果存在任何文本)。

4. 添加字符到显示

# Function to append characters to the entry field
def add_character_to_display(character):
    display.insert(tk.END, character)

add_character_to_display 函数将指定的字符附加到显示中的当前文本。此函数对于一次构建一个字符的数学表达式至关重要。

5. 计算平方根

# Function to calculate the square root of the current value
def calculate_square_root():
    try:
        result = math.sqrt(eval(display.get()))
        display.delete(0, tk.END)
        display.insert(tk.END, str(result))
    except Exception as e:
        display.delete(0, tk.END)
        display.insert(tk.END, "Error")

此函数计算显示中值的平方根。它首先计算当前表达式,然后应用 math.sqrt 函数来计算平方根。如果计算成功,则显示结果;否则,将显示 “Error”。

6. 创建应用程序窗口

# Create the main application window
app_window = tk.Tk()
app_window.title("Basic Calculator")

我们使用 tk 初始化主应用程序窗口。Tk(),它为计算器创建根窗口。窗口的标题设置为 “Basic Calculator”。

7. 用于显示的输入字段

# Create an entry field for displaying input and results
display = tk.Entry(app_window, width=30, font=("Arial", 14))
display.grid(row=0, column=0, columnspan=5, padx=10, pady=10)

显示屏是一个显示用户输入和结果的入口小部件。它的宽度为 30 个字符,并使用 Arial 字体大小 14 以提高可读性。它位于窗口顶部,跨越五列。

8. 按钮布局和功能分配

# Define the layout of the calculator buttons
buttons = [
    ['(', ')', '←', 'Clear', '√'],
    ['7', '8', '9', '/'],
    ['4', '5', '6', '*'],
    ['1', '2', '3', '-'],
    ['0', '.', '=', '+']
]

按钮以网格布局排列,每个子列表代表一行按钮。此布局有助于在 GUI 中以逻辑方式组织按钮。

9. 按钮创建和分配

# Create the buttons and assign them functions
for r, button_row in enumerate(buttons, start=1):
    for c, button_text in enumerate(button_row):
        if button_text == '=':
            btn = tk.Button(app_window, text=button_text, width=10, command=calculate_expression)
        elif button_text == 'Clear':
            btn = tk.Button(app_window, text=button_text, width=10, command=clear_display)
        elif button_text == '←':
            btn = tk.Button(app_window, text=button_text, width=5, command=delete_last_character)
        elif button_text == '√':
            btn = tk.Button(app_window, text=button_text, width=10, command=calculate_square_root)
        else:
            btn = tk.Button(app_window, text=button_text, width=5, command=lambda char=button_text: add_character_to_display(char))


        btn.grid(row=r, column=c, padx=5, pady=5)

按钮根据其标签创建并分配特定功能。例如,等于按钮链接到calculate_expression,清除按钮链接到clear_display。其他按钮(如数字和运算符)将 add_character_to_display 与各自的文本一起使用。

10. 网格配置

# Allow the grid to resize with the window
for i in range(5):
    app_window.grid_columnconfigure(i, weight=1)
for i in range(6):
    app_window.grid_rowconfigure(i, weight=1)

网格布局配置为与窗口按比例调整大小,确保无论窗口大小如何,界面都保持一致且用户友好。

11. 启动应用程序

# Start the Tkinter main loop
app_window.mainloop()

app_window.mainloop() 调用启动 Tkinter 事件循环,使应用程序保持运行并响应用户输入。此循环一直持续到用户关闭窗口。

完整代码:

import tkinter as tk
import math


# Function to evaluate the expression
def calculate_expression():
    try:
        result = eval(display.get())
        display.delete(0, tk.END)
        display.insert(tk.END, str(result))
    except Exception as e:
        display.delete(0, tk.END)
        display.insert(tk.END, "Error")


# Function to clear the entry field
def clear_display():
    display.delete(0, tk.END)


# Function to delete the last character from the entry field
def delete_last_character():
    current_text = display.get()
    if current_text:
        display.delete(len(current_text) - 1, tk.END)


# Function to append characters to the entry field
def add_character_to_display(character):
    display.insert(tk.END, character)


# Function to calculate the square root of the current value
def calculate_square_root():
    try:
        result = math.sqrt(eval(display.get()))
        display.delete(0, tk.END)
        display.insert(tk.END, str(result))
    except Exception as e:
        display.delete(0, tk.END)
        display.insert(tk.END, "Error")


# Create the main application window
app_window = tk.Tk()
app_window.title("Basic Calculator")


# Create an entry field for displaying input and results
display = tk.Entry(app_window, width=30, font=("Arial", 14))
display.grid(row=0, column=0, columnspan=5, padx=10, pady=10)


# Define the layout of the calculator buttons
buttons = [
    ['(', ')', '←', 'Clear', '√'],
    ['7', '8', '9', '/'],
    ['4', '5', '6', '*'],
    ['1', '2', '3', '-'],
    ['0', '.', '=', '+']
]


# Create the buttons and assign them functions
for r, button_row in enumerate(buttons, start=1):
    for c, button_text in enumerate(button_row):
        if button_text == '=':
            btn = tk.Button(app_window, text=button_text, width=10, command=calculate_expression)
        elif button_text == 'Clear':
            btn = tk.Button(app_window, text=button_text, width=10, command=clear_display)
        elif button_text == '←':
            btn = tk.Button(app_window, text=button_text, width=5, command=delete_last_character)
        elif button_text == '√':
            btn = tk.Button(app_window, text=button_text, width=10, command=calculate_square_root)
        else:
            btn = tk.Button(app_window, text=button_text, width=5, command=lambda char=button_text: add_character_to_display(char))


        btn.grid(row=r, column=c, padx=5, pady=5)


# Allow the grid to resize with the window
for i in range(5):
    app_window.grid_columnconfigure(i, weight=1)
for i in range(6):
    app_window.grid_rowconfigure(i, weight=1)


# Start the Tkinter main loop
app_window.mainloop()

Python 计算器输出

结论

使用 Python 和 Tkinter 开发的 Basic Calculator 应用程序演示了如何创建能够执行基本算术运算的功能互式计算器。

该代码的结构用于处理用户输入、有效管理错误,并提供平方根计算和字符删除等附加功能。

该项目是对 Python 中 GUI 开发的出色介绍,并为将来更复杂的应用程序提供了坚实的基础。将 Tkinter 用于 GUI 和数学用于计算凸显了 Python 在构建实用且用户友好的软件工具方面的多功能性。

相关推荐

推荐一款Python的GUI可视化工具(python 可视化工具)

在Python基础语法学习完成后,进一步开发应用界面时,就需要涉及到GUI了,GUI全称是图形用户界面(GraphicalUserInterface,又称图形用户接口),采用图形方式显示的计算机操...

教你用Python绘制谷歌浏览器的3种图标

前两天在浏览matplotlib官方网站时,笔者无意中看到一个挺有意思的图片,就是用matplotlib制作的火狐浏览器的logo,也就是下面这个东东(网页地址是https://matplotlib....

小白学Python笔记:第二章 Python安装

Windows操作系统的python安装:Python提供Windows、Linux/UNIX、macOS及其他操作系统的安装包版本,结合自己的使用情况,此处仅记录windows操作系统的python...

Python程序开发之简单小程序实例(9)利用Canvas绘制图形和文字

Python程序开发之简单小程序实例(9)利用Canvas绘制图形和文字一、项目功能利用Tkinter组件中的Canvas绘制图形和文字。二、项目分析要在窗体中绘制图形和文字,需先导入Tkinter组...

一文吃透Python虚拟环境(python虚拟环境安装和配置)

摘要在Python开发中,虚拟环境是一种重要的工具,用于隔离不同项目的依赖关系和环境配置。本文将基于windows平台介绍四种常用的Python虚拟环境创建工具:venv、virtualenv、pip...

小白也可以玩的Python爬虫库,收藏一下

最近,微软开源了一个项目叫「playwright-python」,作为一个兴起项目,出现后受到了大家热烈的欢迎,那它到底是什么样的存在呢?今天为你介绍一下这个传说中的小白神器。Playwright是...

python环境安装+配置教程(python安装后怎么配置环境变量)

安装python双击以下软件:弹出一下窗口需选择一些特定的选项默认选项不需要更改,点击next勾选以上选项,点击install进度条安装完毕即可。到以下界面,证明安装成功。接下来安装库文件返回电脑桌面...

colorama,一个超好用的 Python 库!

大家好,今天为大家分享一个超好用的Python库-colorama。Github地址:https://github.com/tartley/coloramaPythoncolorama库是一...

python制作仪表盘图(python绘制仪表盘)

今天教大家用pyecharts画仪表盘仪表盘(Gauge)是一种拟物化的图表,刻度表示度量,指针表示维度,指针角度表示数值。仪表盘图表就像汽车的速度表一样,有一个圆形的表盘及相应的刻度,有一个指针...

总结90条写Python程序的建议(python写作)

  1.首先  建议1、理解Pythonic概念—-详见Python中的《Python之禅》  建议2、编写Pythonic代码  (1)避免不规范代码,比如只用大小写区分变量、使用容易...

[oeasy]python0137_相加运算_python之禅_import_this_显式转化

变量类型相加运算回忆上次内容上次讲了是从键盘输入变量input函数可以有提示字符串需要有具体的变量接收输入的字符串输入单个变量没有问题但是输入两个变量之后一相加就非常离谱添加图片注释,不超过1...

Python入门学习记录之一:变量(python中变量的规则)

写这个,主要是对自己学习python知识的一个总结,也是加深自己的印象。变量(英文:variable),也叫标识符。在python中,变量的命名规则有以下三点:>变量名只能包含字母、数字和下划线...

掌握Python的"魔法":特殊方法与属性完全指南

在Python的世界里,以双下划线开头和结尾的"魔法成员"(如__init__、__str__)是面向对象编程的核心。它们赋予开发者定制类行为的超能力,让自定义对象像内置类型一样优雅工...

11个Python技巧 不Pythonic 实用大于纯粹

虽然Python有一套强大的设计哲学(体现在“Python之禅”中),但总有一些情况需要我们“打破规则”来解决特定问题。这触及了Python哲学中一个非常核心的理念:“实用主义胜于纯粹主义”...

Python 从入门到精通 第三课 诗意的Python之禅

导言:Python之禅,英文名是TheZenOfPython。最早由TimPeters在Python邮件列表中发表,它包含了影响Python编程语言设计的20条软件编写原则。它作为复活节彩蛋...

取消回复欢迎 发表评论: