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

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

off999 2024-10-02 18:35 19 浏览 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 数据分析——利用Pandas进行分组统计

话说天下大势,分久必合,合久必分。数据分析也是如此,我们经常要对数据进行分组与聚合,以对不同组的数据进行深入解读。本章将介绍如何利用Pandas中的GroupBy操作函数来完成数据的分组、聚合以及统计...

python数据分析:介绍pandas库的数据类型Series和DataFrame

安装pandaspipinstallpandas-ihttps://mirrors.aliyun.com/pypi/simple/使用pandas直接导入即可importpandasas...

使用DataFrame计算两列的总和和最大值_[python]

【如果对您有用,请关注并转发,谢谢~~】最近在处理气象类相关数据的空间计算,在做综合性计算的时候,DataFrame针对每列的统计求和、最大值等较为方便,对某行的两列或多列数据进行求和与最大值等的简便...

8-Python内置函数

Python提供了丰富的内置函数,这些函数可以直接使用而无需导入任何模块。以下是一些常用的内置函数及其示例:1-print()1-1-说明输出指定的信息到控制台。1-2-例子2-len()2-1-说...

Python中函数式编程函数: reduce()函数

Python中的reduce()函数是一个强大的工具,它通过连续地将指定的函数应用于序列(如列表)来对序列(如列表)执行累积操作。它是functools模块的一部分,这意味着您需要在使用它之...

万万没想到,除了香农计划,Python3.11竟还有这么多性能提升

众所周知,Python3.11版本带来了较大的性能提升,但是,它具体在哪些方面上得到了优化呢?除了著名的“香农计划”外,它还包含哪些与性能相关的优化呢?本文将带你一探究竟!作者:BeshrKay...

最全python3.11版12类75个内置函数大全

获取全部内置函数:importbuiltins#导入模块yc=[]#异常属性nc=[]#不可调用fn=[]#内置函数defll(ty=builtins):...

软件测试笔试题

测试工程师岗位,3-5年,10-14k1.我司有一款产品,类似TeamViewer,向日葵,mstsc,QQ远程控制产品,一个PC客户端产品,请设想一下测试要点。并写出2.写出常用的SQL语句8条,l...

备战各大互联网巨头公司招聘会,最全Python面试大全,共300题

前言众所周知,越是顶尖的互联网公司在面试这一part的要求就越高,需要你有很好的技术功底、项目经验、一份漂亮的简历,当然还有避免不了的笔试过关。对于Python的工程师来说,全面掌握好有关Python...

经典 SQL 数据库笔试题及答案整理

马上又是金三银四啦,有蛮多小伙伴在跳槽找工作,但对于年限稍短的软件测试工程师,难免会需要进行笔试,而在笔试中,基本都会碰到一道关于数据库的大题,今天这篇文章呢,就收录了下最近学员反馈上来的一些数据库笔...

用Python开发日常小软件,让生活与工作更高效!附实例代码

引言:Python如何让生活更轻松?在数字化时代,编程早已不是程序员的专属技能。Python凭借其简洁易学的特点,成为普通人提升效率、解决日常问题的得力工具。无论是自动化重复任务、处理数据,还是开发个...

太牛了!102个Python实战项目被我扒到了!建议收藏!

挖到宝了!整整102个Python实战项目合集,从基础语法到高阶应用全覆盖,附完整源码+数据集,手把手带你从代码小白变身实战大神!这波羊毛不薅真的亏到哭!超全项目库,学练一站式搞定这份资...

Python中的并发编程

1.Python对并发编程的支持多线程:threading,利用CPU和IO可以同时执行的原理,让CPU不会干巴巴等待IO完成。多进程:multiprocessing,利用多核CPU...

Python 也有内存泄漏?

1.背景前段时间接手了一个边缘视觉识别的项目,大功能已经开发的差不多了,主要是需要是优化一些性能问题。其中比较突出的内存泄漏的问题,而且不止一处,有些比较有代表性,可以总结一下。为了更好地可视化内存...

python爬虫之多线程threading、多进程、协程aiohttp批量下载图片

一、单线程常规下载常规单线程执行脚本爬取壁纸图片,只爬取一页的图片。importdatetimeimportreimportrequestsfrombs4importBeautifu...

取消回复欢迎 发表评论: