ITPub博客

首页 > 数据库 > 数据库开发技术 > 用python写一个简单的计算器

用python写一个简单的计算器

原创 数据库开发技术 作者:心一信息 时间:2024-05-09 19:04:00 0 删除 编辑

今天实现一下用python写一个简单的计算器,在编写计算器时,这里要用到的是tkinter模块。

Tkinter是Python内置的图形用户界面(GUI)模块,它提供了创建GUI应用程序所需的所有组件和工具。它使用Tcl/Tk工具包来实现GUI,因此可以在多个平台上运行,包括Windows、Linux和Mac OS X等。

Tkinter包含了许多常用的GUI组件,如按钮、标签、文本框、滚动条、菜单等,同时也支持自定义组件的开发。在使用Tkinter时,需要创建一个主窗口,并在该窗口中添加所需的组件,最后通过事件处理机制来实现用户与应用程序的交互。

按之前的步骤新建工程,新建python文件命名为calc,在文件里写入下列代码

import tkinter as tkimport math
class Calculator: def __init__(self, master): self.master = master master.title("Calculator")
# GUI界面参数 self.display = tk.Entry(master, width=25, font=('Arial', 16)) self.display.grid(row=0, column=0, columnspan=4, padx=5, pady=5)
# 定义按钮 buttons = [ '7', '8', '9', '/', '4', '5', '6', '*', '1', '2', '3', '-', '0', '.', '=', '+', 'C', 'x^2', 'x^3', 'x^n', 'sqrt', 'log10', 'ln' ] row = 1 col = 0 for button in buttons: command = lambda x=button: self.button_click(x) tk.Button(master, text=button, width=5, height=2, command=command).grid(row=row, column=col, padx=5, pady=5) col += 1 if col > 3: col = 0 row += 1 #定义各个按钮的功能 def button_click(self, key): if key == '=': result = eval(self.display.get()) self.display.delete(0, tk.END) self.display.insert(0, str(result)) elif key == 'C': self.display.delete(0, tk.END) elif key == 'x^2': x = float(self.display.get()) result = x ** 2 self.display.delete(0, tk.END) self.display.insert(0, str(result)) elif key == 'x^3': x = float(self.display.get()) result = x ** 3 self.display.delete(0, tk.END) self.display.insert(0, str(result)) elif key == 'sqrt': x = float(self.display.get()) result = math.sqrt(x) self.display.delete(0, tk.END) self.display.insert(0, str(result)) elif key == 'log10': x = float(self.display.get()) result = math.log10(x) self.display.delete(0, tk.END) self.display.insert(0, str(result)) elif key == 'ln': x = float(self.display.get()) result = math.log(x) self.display.delete(0, tk.END) self.display.insert(0, str(result)) elif key == 'x^n': x = float(self.display.get()) self.display.delete(0, tk.END) self.display.insert(0, str(x) + '^') else: self.display.insert(tk.END, key)
root = tk.Tk()calc = Calculator(root)root.mainloop()

在pycharm里测试一下:

按照之前的教程仍然需要在终端内安装pyinstaller,代码大家很熟悉的pip install pyinstaller

不会配置环境变量没关系,按照我下面的方法同样可以。

复制工程的绝对路径,如C:\Users\Administrator\PycharmProjects\pythonProject3(工程名字自行类比下)。在cmd命令行内cd 到下级文件夹,\venv\scripts\ 刚在装的 pyinstaller在这个下面

如上显示。再说一个小技巧,在地址栏内写入cmd,则直接在该目录下面打开命令行,如下图

将你工程里编写的文件复制到这个文件夹下面,我写了calc和calc2.0两个,那么cmd里直接输入:

pyinstaller calc.py

则将该python全部整合到dist里面的可执行文件。

运行下面的calc.exe即可执行。


原文作者:心一信息;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2023-06-30

  • 博文量
    200
  • 访问量
    94063