吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 4156|回复: 34
收起左侧

[Python 原创] 一个可以将py代码打包成独立exe文件的工具

  [复制链接]
Hf6824329 发表于 2025-7-30 14:21
链接: https://pan.baidu.com/s/1Q42sNsgcoMrKQiKMPVybqg?pwd=hzhz 提取码: hzhz
Snipaste_2025-07-30_11-05-54.png
[Python] 纯文本查看 复制代码
import os
import subprocess
import sys
import time
import tkinter as tk
from tkinter import ttk, filedialog, scrolledtext

# 尝试导入psutil,如果不存在则在后续代码中处理
try:
    import psutil
    import PyInstaller
    import PIL
    import pandas
    import openpyxl
    HAS_PSUTIL = True
except ImportError:
    HAS_PSUTIL = False

class PackageGUI:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("py代码打包ExEh工具")
        self.root.geometry("800x600")
        
        # 创建主框架
        self.main_frame = ttk.Frame(self.root, padding="10")
        self.main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 输入文件选择
        ttk.Label(self.main_frame, text="输入文件:").pack(anchor=tk.W)
        self.input_frame = ttk.Frame(self.main_frame)
        self.input_frame.pack(fill=tk.X, pady=5)
        self.input_path = tk.StringVar()
        ttk.Entry(self.input_frame, textvariable=self.input_path).pack(side=tk.LEFT, fill=tk.X, expand=True)
        ttk.Button(self.input_frame, text="浏览", command=self.select_input).pack(side=tk.RIGHT)
        
        # 输出目录选择
        ttk.Label(self.main_frame, text="输出目录:").pack(anchor=tk.W)
        self.output_frame = ttk.Frame(self.main_frame)
        self.output_frame.pack(fill=tk.X, pady=5)
        self.output_path = tk.StringVar()
        ttk.Entry(self.output_frame, textvariable=self.output_path).pack(side=tk.LEFT, fill=tk.X, expand=True)
        ttk.Button(self.output_frame, text="浏览", command=self.select_output).pack(side=tk.RIGHT)

        # 输出文件名称
        ttk.Label(self.main_frame, text="输出文件名称:").pack(anchor=tk.W)
        self.output_name_frame = ttk.Frame(self.main_frame)
        self.output_name_frame.pack(fill=tk.X, pady=5)
        self.output_name = tk.StringVar(value="文件名称批量获取工具")
        ttk.Entry(self.output_name_frame, textvariable=self.output_name).pack(side=tk.LEFT, fill=tk.X, expand=True)
        
        # 调试模式选项
        self.debug_mode = tk.BooleanVar()
        ttk.Checkbutton(self.main_frame, text="调试模式", variable=self.debug_mode).pack(anchor=tk.W, pady=5)
        
        # 日志显示区域
        ttk.Label(self.main_frame, text="打包日志:").pack(anchor=tk.W)
        self.log_text = scrolledtext.ScrolledText(self.main_frame, height=20)
        self.log_text.pack(fill=tk.BOTH, expand=True, pady=5)
        
        # 按钮区域
        self.button_frame = ttk.Frame(self.main_frame)
        self.button_frame.pack(fill=tk.X, pady=10)
        ttk.Button(self.button_frame, text="开始打包", command=self.start_package).pack(side=tk.RIGHT)
        
    def select_input(self):
        filename = filedialog.askopenfilename(filetypes=[("Python Files", "*.py")])
        if filename:
            self.input_path.set(filename)
            
    def select_output(self):
        dirname = filedialog.askdirectory()
        if dirname:
            self.output_path.set(dirname)
            
    def log(self, message):
        self.log_text.insert(tk.END, message + "\n")
        self.log_text.see(tk.END)
        self.root.update()
        
    def start_package(self):
        self.log("开始打包流程...")
        
        # 检查必要的库
        if not self.check_requirements():
            return
            
        # 打包应用
        if self.package_app():
            self.log("\n打包过程完成!您可以分发生成的exe文件给其他用户使用。")
        else:
            self.log("\n打包过程未成功完成,请检查上述错误信息。")
    
    def check_requirements(self):
        # 检查并安装必要的库
        try:
            import PyInstaller
            self.log("检测到PyInstaller已安装")
        except ImportError:
            self.log("无法继续打包过程,请手动安装PyInstaller后重试。")
            return False
            
        try:
            import PIL
            self.log("检测到Pillow已安装")
        except ImportError:
            self.log("警告:Pillow库安装失败,可能无法正确处理自定义图标。")
            
        try:
            import pandas
            import openpyxl
            self.log("检测到pandas和openpyxl已安装")
        except ImportError:
            self.log("警告:pandas或openpyxl库安装失败,可能无法正确支持Excel导出功能。")
            
        return True
        
    def check_icon_file(self):
        """检查图标文件是否存在"""
        icon_path = os.path.join(os.path.dirname(self.input_path.get()), "app_icon.ico")
        return os.path.exists(icon_path)
        
    def package_app(self):
        input_file = self.input_path.get()
        output_dir = self.output_path.get()
        output_name = self.output_name.get()
        
        if not input_file or not os.path.exists(input_file):
            self.log("错误:请选择有效的输入文件")
            return False
            
        if not output_dir:
            self.log("错误:请选择输出目录")
            return False

        if not output_name:
            self.log("错误:请输入输出文件名称")
            return False
            
        # 构建PyInstaller命令
        cmd = [
            sys.executable,
            "-m",
            "PyInstaller",
            f"--name={output_name}",
            "--onefile",
            "--hidden-import=pandas",
            "--hidden-import=openpyxl",
            f"--distpath={output_dir}"
        ]
        
        if self.debug_mode.get():
            cmd.extend(["--console", "--debug=all"])
        else:
            cmd.append("--windowed")
            
        # 检查图标文件
        if self.check_icon_file():
            cmd.append("--icon=" + os.path.join(os.path.dirname(input_file), "app_icon.ico"))
            
        cmd.append(input_file)
        
        try:
            # 执行打包命令
            process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
            
            # 实时显示输出
            while True:
                output = process.stdout.readline()
                if output == '' and process.poll() is not None:
                    break
                if output:
                    self.log(output.strip())
                    
            return process.poll() == 0
            
        except Exception as e:
            self.log(f"打包过程出错: {e}")
            return False
            
def main():
    app = PackageGUI()
    app.root.mainloop()

if __name__ == "__main__":
    main()

免费评分

参与人数 6吾爱币 +12 热心值 +5 收起 理由
djgsdj + 1 + 1 谢谢@Thanks!
lin_xop + 1 + 1 热心回复!
追逐飞翔 + 1 + 1 热心回复!
skip2 + 1 + 1 谢谢@Thanks!
hrh123 + 7 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!
yanglinman + 1 谢谢@Thanks!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

pc_sen 发表于 2025-7-30 15:50
为什么点击开始打包后,又新自动弹出来个一样的程序,在点击新的页面上开始打包,又弹出来个。
iawyxkdn8 发表于 2025-7-30 16:32
看到有人要其他不限速的盘,整了一个LZ,感谢作者的无私分享!
https://wwkp.lanzoum.com/ik8Rd326n3wf
密码:37wb
happyafish 发表于 2025-7-30 17:33
 楼主| Hf6824329 发表于 2025-7-30 16:54
wen4610078 发表于 2025-7-30 15:18
有代码纠错功能吗?博主

木有啊,py没问题肯定可以打包的;会先拉取依赖的
Airiair 发表于 2025-7-30 16:18
能连同环境一起打包吗
wen4610078 发表于 2025-7-30 15:18
有代码纠错功能吗?博主
开创者 发表于 2025-7-30 15:27
做了个py的网站,打包成功了,不能用
蛋蛋的小忧伤 发表于 2025-7-30 15:27
坐等其他网盘,百度下不了一点
yzqdev 发表于 2025-7-30 16:33
可以根据pyinstaller的参数做几个下拉菜单,相当于可视化了
 楼主| Hf6824329 发表于 2025-7-30 16:55
yzqdev 发表于 2025-7-30 16:33
可以根据pyinstaller的参数做几个下拉菜单,相当于可视化了

源代码发放出来了,接下来靠各位开源人拓展了
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - 52pojie.cn ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2026-8-13 00:00

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表