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

用Python制作一个带图形界面的计算器

itomcoil 2025-05-28 17:52 11 浏览

大家好,今天我要带大家使用Python制作一个具有图形界面的计算器应用程序。这个项目不仅可以帮助你巩固Python编程基础,还可以让你初步体验图形化编程的乐趣。我们将使用Python的tkinter库,它是一个简单易用的GUI库,非常适合用来开发小型的桌面应用。

一、项目简介

在我们日常生活中,计算器是一个不可或缺的工具。通过本项目,你将学会如何用Python创建一个类似Windows系统自带计算器的应用程序,实现基本的加、减、乘、除等运算功能。最终效果将是一个带有数字按钮、运算符按钮和显示屏的完整计算器。

二、准备工作

首先,你需要确保你的Python环境中已经安装了tkinter库。幸运的是,如果你已经安装了Python,那么tkinter库一般会随Python一起安装,无需额外操作。

接下来,我们将一步步构建这个计算器。

三、构建图形界面

  1. 创建主窗口和输入框

我们首先需要创建一个主窗口,并在窗口中放置一个用于显示计算结果的输入框。代码如下:

import tkinter as tk

# 创建主窗口
root = tk.Tk()
root.title("Python 计算器")

# 输入框
entry = tk.Entry(root, width=16, font=('Arial', 24), borderwidth=2, relief="solid")
entry.grid(row=0, column=0, columnspan=4)

在这段代码中,tk.Tk()用来创建一个主窗口,tk.Entry()则创建了一个输入框,设置了字体大小和边框样式。最后,通过grid方法将输入框放置在网格的第一行,并跨越四列。

  1. 实现按钮点击事件

接下来,我们定义一些函数来处理按钮的点击事件。我们需要处理三种类型的按钮:数字按钮、运算符按钮和功能按钮(如等号和清除)。

# 全局变量来存储计算器的状态
current = ""
operator = ""

# 按钮点击事件
def button_click(number):
    global current
    current += str(number)
    entry.delete(0, tk.END)
    entry.insert(tk.END, current)

def button_clear():
    global current, operator
    current = ""
    operator = ""
    entry.delete(0, tk.END)

def button_equal():
    global current, operator
    try:
        result = str(eval(current))
        entry.delete(0, tk.END)
        entry.insert(tk.END, result)
        current = result
    except:
        entry.delete(0, tk.END)
        entry.insert(tk.END, "Error")
        current = ""

在这里,button_click函数用来处理数字和运算符按钮的点击,button_clear清除输入框的内容,button_equal则用于计算输入的表达式并显示结果。

  1. 创建和布局按钮

计算器的每个按钮(数字键和运算符键)都需要创建,并通过grid方法放置在窗口中的合适位置。

# 创建按钮
button_1 = tk.Button(root, text="1", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click(1))
button_2 = tk.Button(root, text="2", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click(2))
button_3 = tk.Button(root, text="3", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click(3))
button_4 = tk.Button(root, text="4", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click(4))
button_5 = tk.Button(root, text="5", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click(5))
button_6 = tk.Button(root, text="6", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click(6))
button_7 = tk.Button(root, text="7", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click(7))
button_8 = tk.Button(root, text="8", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click(8))
button_9 = tk.Button(root, text="9", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click(9))
button_0 = tk.Button(root, text="0", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click(0))

button_add = tk.Button(root, text="+", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click('+'))
button_subtract = tk.Button(root, text="-", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click('-'))
button_multiply = tk.Button(root, text="*", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click('*'))
button_divide = tk.Button(root, text="/", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click('/'))
button_equal = tk.Button(root, text="=", padx=20, pady=20, font=('Arial', 18), command=button_equal)
button_clear = tk.Button(root, text="C", padx=20, pady=20, font=('Arial', 18), command=button_clear)

# 布局按钮
button_1.grid(row=3, column=0)
button_2.grid(row=3, column=1)
button_3.grid(row=3, column=2)

button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)

button_7.grid(row=1, column=0)
button_8.grid(row=1, column=1)
button_9.grid(row=1, column=2)

button_0.grid(row=4, column=0)

button_add.grid(row=1, column=3)
button_subtract.grid(row=2, column=3)
button_multiply.grid(row=3, column=3)
button_divide.grid(row=4, column=3)

button_equal.grid(row=4, column=2)
button_clear.grid(row=4, column=1)

上面的代码定义了数字按钮(0-9)和运算符按钮(+,-,*,/),并且通过grid方法将它们放置在不同的行和列中,构成了一个标准的计算器布局。

  1. 启动应用程序

最后一步,我们通过root.mainloop()启动主循环,运行我们的应用程序。

# 启动主循环
root.mainloop()

这行代码会让我们的程序进入一个无限循环状态,等待用户的操作。

四、完整代码

下面是我们构建的完整代码:

import tkinter as tk

# 创建主窗口
root = tk.Tk()
root.title("Python 计算器")

# 输入框
entry = tk.Entry(root, width=16, font=('Arial', 24), borderwidth=2, relief="solid")
entry.grid(row=0, column=0, columnspan=4)

# 全局变量来存储计算器的状态
current = ""
operator = ""

# 按钮点击事件
def button_click(number):
    global current
    current += str(number)
    entry.delete(0, tk.END)
    entry.insert(tk.END, current)

def button_clear():
    global current, operator
    current = ""
    operator = ""
    entry.delete(0, tk.END)

def button_equal():
    global current, operator
    try:
        result = str(eval(current))
        entry.delete(0, tk.END)
        entry.insert(tk.END, result)
        current = result
    except:
        entry.delete(0, tk.END)
        entry.insert(tk.END, "Error")
        current = ""

# 创建按钮
button_1 = tk.Button(root, text="1", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click(1))
button_2 = tk.Button(root, text="2", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click(2))
button_3 = tk.Button(root, text="3", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click(3))
button_4 = tk.Button(root, text="4", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click(4))
button_5 = tk.Button(root, text="5", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click(5))
button_6 = tk.Button(root, text="6", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click(6))
button_7 = tk.Button(root, text="7", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click(7))
button_8 = tk.Button(root, text="8", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click(8))
button_9 = tk.Button(root, text="9", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click(9))
button_0 = tk.Button(root, text="0", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click(0))

button_add = tk.Button(root, text="+", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click('+'))
button_subtract = tk.Button(root, text="-", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click('-'))
button_multiply = tk.Button(root, text="*", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click('*'))
button_divide = tk.Button(root, text="/", padx=20, pady=20, font=('Arial', 18), command=lambda: button_click('/'))
button_equal = tk.Button(root, text="=", padx=20, pady=20, font=('Arial', 18), command=button_equal)
button_clear = tk.Button(root, text="C", padx=20, pady=20, font=('Arial', 18), command=button_clear)

# 布局按钮
button_1.grid(row=3, column=0)
button_2.grid(row=3, column=1)
button_3.grid(row=3, column=2)

button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)

button_7.grid(row=1, column=0)
button_8.grid(row=1, column=1)
button_9.grid(row=1, column=2)

button_0.grid(row=4, column=0)

button_add.grid(row=1, column=3)
button_subtract.grid(row=2, column=3)
button_multiply.grid(row=3, column=3)
button_divide.grid(row=4, column=3)

button_equal.grid(row=4, column=2)
button_clear.grid(row=4, column=1)

# 启动主循环
root.mainloop()

五、总结

这个Python计算器项目展示了如何使用tkinter库创建一个基本的GUI应用程序。虽然这个计算器功能简单,但它涵盖了Python编程的许多基本概念,例如事件处理、函数定义、全局变量的使用,以及图形界面的布局管理。通过这个项目,相信大家能够对Python的图形化编程有一个更直观的了解。如果你觉得这篇文章对你有帮助,欢迎分享给更多的朋友!


相关推荐

Python字符串格式化:你真的会用吗?告别混乱代码,看这一篇就够

大家好!今天我们来聊聊Python中一个看似简单却暗藏玄机的操作——字符串格式化。你是不是还在用%s拼凑变量?或者写了无数个format()却依然被同事吐槽代码太“复古”?别急,这篇干货带你解锁三种神...

Python Unicode字符串编程实用教程

Unicode是现代文本处理的基础,本教程将介绍Python中的Unicode字符串处理,涵盖从基础概念到高级应用等。一、Unicode基础概念1.1Unicode与编码核心概念:Unicode:字...

殊途同归 python 第 6 节:字符串的使用

字符串作为Python的基础数据之一,以下是字符串的几种最常用情形,直接上代码1.声明字符串a="helloworld"b='竹杖芒鞋轻胜马,谁怕,一蓑烟雨任平生...

python爬虫字符串定位开始跟结束(find方法的使用)

python爬虫采集的时候会需要对采集的内容进行处理行为,处理什么?简单的说就是处理多余的HTML代码跟确定文章标题跟结尾,还有内容区间,方法如下:首先先是定位,我们先假设我们采集到了一批数据,数据里...

python 入门到脱坑 基本数据类型—字符串string

以下是Python字符串(String)的入门详解,包含基础操作、常用方法和实用技巧,适合初学者快速掌握:一、字符串基础1.定义字符串#单引号/双引号s1='hello's...

python字符串知识点总结

Python字符串知识点总结1.字符串基础字符串是不可变的序列类型可以用单引号(')、双引号(")或三引号('''或""")创建三引号...

在 Python 中使用 f-String 格式化字符串

在Python3.6中引入的f字符串提供了一种既简洁又可读的字符串格式新方法。f字符串的正式名称为格式化字符串文字,是以f或F为前缀的字符串,其中包含大括号内的表达式。这些表达式在...

零起点Python机器学习快速入门-4-3-字符串常用方法

Python中字符串的多种操作。包括去除字符串首尾的空格和特定字符、字符串的连接、查找字符在字符串中的位置、字符串之间的比较、计算字符串的长度、大小写转换以及字符串的分割。通过这些操作,我们可以对字...

Python 中 字符串处理的高效方法,不允许你还不知道

以下是Python中字符串处理的高效方法,涵盖常用操作、性能优化技巧和实际应用场景,帮助您写出更简洁、更快速的代码:一、基础高效操作1.字符串拼接:优先用join()代替+原因:join()预...

Python字符串详解与示例

艾瑞巴蒂字符串的干货来了,字符串是程序中最常见的数据类型之一,用来表示数据文本,下面就来介绍下字符串的特性,操作和方法,和一些示例来吧道友:1.字符串的创建在python中字符串可以永单引号(...

Python中去除字符串末尾换行符的方法

技术背景在Python编程中,处理字符串时经常会遇到字符串末尾包含换行符的情况,如从文件中读取每一行内容时,换行符会作为字符串的一部分被读取进来。为了满足后续处理需求,需要将这些换行符去除。实现步骤1...

表格编程之争:Python VS VBA?Excel用户:新编程语言才真香!

Python和VBA哪个更好用?Python和VBA是两种不同的编程语言,它们都有自己的特点和优缺点。在表格编程方面,VBA在Excel中的应用非常广泛,可以通过宏来实现自动化操作和数据处理,也可以通...

用Python把表格做成web可视化图表

Python中有一个streamlit库,Streamlit的美妙之处在于您可以直接在Python中创建Web应用程序,而无需了解HTML、CSS或JavaScrip,今天我们就用st...

使用 Python 在 PowerPoint 演示文稿中创建或提取表格

PowerPoint中的表格是一种以结构化格式组织和呈现数据的方法,类似于Excel或Word等其他应用程序中表格的使用方式。它们提供了一种清晰简洁的方式来显示信息,使您的受众更容易消化和理...

用python实现打印表格的方法

最近在做表格输出的任务,一般有两种方法实现在控制台打印,一种是根据表格的输出规则自己写代码实现,另外一种是安装python的第三方依赖包prettytable实现这个效果。方法1:根据表格规则写代码...