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

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

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

大家好,今天我要带大家使用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的图形化编程有一个更直观的了解。如果你觉得这篇文章对你有帮助,欢迎分享给更多的朋友!


相关推荐

selenium(WEB自动化工具)

定义解释Selenium是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。支持的浏览器包括IE(7,8,9,10,11),MozillaF...

开发利器丨如何使用ELK设计微服务中的日志收集方案?

【摘要】微服务各个组件的相关实践会涉及到工具,本文将会介绍微服务日常开发的一些利器,这些工具帮助我们构建更加健壮的微服务系统,并帮助排查解决微服务系统中的问题与性能瓶颈等。我们将重点介绍微服务架构中...

高并发系统设计:应对每秒数万QPS的架构策略

当面试官问及"如何应对每秒几万QPS(QueriesPerSecond)"时,大概率是想知道你对高并发系统设计的理解有多少。本文将深入探讨从基础设施到应用层面的解决方案。01、理解...

2025 年每个 JavaScript 开发者都应该了解的功能

大家好,很高兴又见面了,我是"高级前端进阶",由我带着大家一起关注前端前沿、深入前端底层技术,大家一起进步,也欢迎大家关注、点赞、收藏、转发。1.Iteratorhelpers开发者...

JavaScript Array 对象

Array对象Array对象用于在变量中存储多个值:varcars=["Saab","Volvo","BMW"];第一个数组元素的索引值为0,第二个索引值为1,以此类推。更多有...

Gemini 2.5编程全球霸榜,谷歌重回AI王座,神秘模型曝光,奥特曼迎战

刚刚,Gemini2.5Pro编程登顶,6美元性价比碾压Claude3.7Sonnet。不仅如此,谷歌还暗藏着更强的编程模型Dragontail,这次是要彻底翻盘了。谷歌,彻底打了一场漂亮的翻...

动力节点最新JavaScript教程(高级篇),深入学习JavaScript

JavaScript是一种运行在浏览器中的解释型编程语言,它的解释器被称为JavaScript引擎,是浏览器的一部分,JavaScript广泛用于浏览器客户端编程,通常JavaScript脚本是通过嵌...

一文看懂Kiro,其 Spec工作流秒杀Cursor,可移植至Claude Code

当Cursor的“即兴编程”开始拖累项目质量,AWS新晋IDEKiro以Spec工作流打出“先规范后编码”的系统工程思维:需求-设计-任务三件套一次生成,文档与代码同步落地,复杂项目不...

「晚安·好梦」努力只能及格,拼命才能优秀

欢迎光临,浏览之前点击上面的音乐放松一下心情吧!喜欢的话给小编一个关注呀!Effortscanonlypass,anddesperatelycanbeexcellent.努力只能及格...

JavaScript 中 some 与 every 方法的区别是什么?

大家好,很高兴又见面了,我是姜茶的编程笔记,我们一起学习前端相关领域技术,共同进步,也欢迎大家关注、点赞、收藏、转发,您的支持是我不断创作的动力在JavaScript中,Array.protot...

10个高效的Python爬虫框架,你用过几个?

小型爬虫需求,requests库+bs4库就能解决;大型爬虫数据,尤其涉及异步抓取、内容管理及后续扩展等功能时,就需要用到爬虫框架了。下面介绍了10个爬虫框架,大家可以学习使用!1.Scrapysc...

12个高效的Python爬虫框架,你用过几个?

实现爬虫技术的编程环境有很多种,Java、Python、C++等都可以用来爬虫。但很多人选择Python来写爬虫,为什么呢?因为Python确实很适合做爬虫,丰富的第三方库十分强大,简单几行代码便可实...

pip3 install pyspider报错问题解决

运行如下命令报错:>>>pip3installpyspider观察上面的报错问题,需要安装pycurl。是到这个网址:http://www.lfd.uci.edu/~gohlke...

PySpider框架的使用

PysiderPysider是一个国人用Python编写的、带有强大的WebUI的网络爬虫系统,它支持多种数据库、任务监控、项目管理、结果查看、URL去重等强大的功能。安装pip3inst...

「机器学习」神经网络的激活函数、并通过python实现激活函数

神经网络的激活函数、并通过python实现whatis激活函数感知机的网络结构如下:左图中,偏置b没有被画出来,如果要表示出b,可以像右图那样做。用数学式来表示感知机:上面这个数学式子可以被改写:...