一个具体的 AI 提示词和 Python 自动化打包脚本,演示如何从需求直接生成 .exe 可执行文件

这里为您演示一套完整的“需求 -> AI 提示词 -> Python 自动化工具”方案。

这套方案利用一个通用的 Python 构建工具(或脚本),让 AI 助手(如 Cursor、Claude Code、ChatGPT 或本地 AI Agent)在为你生成代码的同时,自动调用构建流程,直接在目录中输出 .exe 文件

第一步:Copilot / AI 智能体专用的“端到端生成 Prompt”

在向 AI 提交需求时,可以直接使用以下提示词模版。这份提示词明确要求 AI 不仅写出完整业务逻辑,还要包含自动打包逻辑:

Markdown

请帮我开发一个 Windows 桌面小工具:【RGB 与 Hex 颜色值实时转换器】。

需求如下:
1. 界面使用 Python 内置的 tkinter,简洁美观,包含颜色预览框。
2. 支持 RGB (0-255) 转 Hex (#RRGGBB) 以及 Hex 转 RGB。
3. 带有“复制到剪贴板”按钮。

【输出与打包要求】:
1. 编写完整的业务代码,保存为 `app.py`。
2. 编写一个名为 `build_exe.py` 的自动化打包脚本:
   - 检查并自动安装 PyInstaller(若未安装)。
   - 自动调用 PyInstaller 将 `app.py` 打包为单一可执行文件(--onefile)且隐藏控制台(--noconsole)。
   - 清理打包过程中产生的 `build/` 临时文件夹和 `.spec` 配置文件。
   - 打包完成后提示用户 `.exe` 的绝对输出路径。
3. 提供一条直接运行 `build_exe.py` 的命令。

第二步:AI 生成的代码实现

1. 业务功能代码:app.py

这是 AI 生成的图形界面逻辑代码:

Python

import tkinter as tk
from tkinter import messagebox

class ColorConverterApp:
    def __init__(self, root):
        self.root = root
        self.root.title("RGB <-> Hex 颜色转换器")
        self.root.geometry("380x320")
        self.root.resizable(False, False)

        # 颜色预览区域
        self.preview_label = tk.Label(root, text="颜色预览", bg="#FFFFFF", fg="#000000", height=3, font=("Microsoft YaHei", 11, "bold"))
        self.preview_label.pack(fill=tk.X, padx=20, pady=15)

        # RGB 输入区
        frame_rgb = tk.Frame(root)
        frame_rgb.pack(pady=5)
        tk.Label(frame_rgb, text="RGB (例: 255, 100, 50):", font=("Microsoft YaHei", 9)).pack(side=tk.LEFT)
        self.entry_rgb = tk.Entry(frame_rgb, width=15)
        self.entry_rgb.pack(side=tk.LEFT, padx=5)
        btn_rgb_convert = tk.Button(frame_rgb, text="转 Hex", command=self.rgb_to_hex)
        btn_rgb_convert.pack(side=tk.LEFT)

        # Hex 输入区
        frame_hex = tk.Frame(root)
        frame_hex.pack(pady=5)
        tk.Label(frame_hex, text="Hex (例: #FF6432):        ", font=("Microsoft YaHei", 9)).pack(side=tk.LEFT)
        self.entry_hex = tk.Entry(frame_hex, width=15)
        self.entry_hex.pack(side=tk.LEFT, padx=5)
        btn_hex_convert = tk.Button(frame_hex, text="转 RGB", command=self.hex_to_rgb)
        btn_hex_convert.pack(side=tk.LEFT)

        # 结果与复制区域
        self.result_var = tk.StringVar(value="等待转换...")
        lbl_result = tk.Label(root, textvariable=self.result_var, font=("Microsoft YaHei", 10, "bold"), fg="#333333")
        lbl_result.pack(pady=15)

        btn_copy = tk.Button(root, text="复制当前结果", command=self.copy_to_clipboard, bg="#0078D4", fg="white", font=("Microsoft YaHei", 9))
        btn_copy.pack(pady=5)

    def update_preview(self, hex_color):
        try:
            self.preview_label.config(bg=hex_color)
            # 根据背景亮度自动调整文字颜色(白/黑)
            r = int(hex_color[1:3], 16)
            g = int(hex_color[3:5], 16)
            b = int(hex_color[5:7], 16)
            brightness = (r * 299 + g * 587 + b * 114) / 1000
            fg_color = "#000000" if brightness > 128 else "#FFFFFF"
            self.preview_label.config(fg=fg_color, text=f"预览: {hex_color.upper()}")
        except Exception:
            pass

    def rgb_to_hex(self):
        text = self.entry_rgb.get().strip()
        try:
            parts = [int(x.strip()) for x in text.split(',')]
            if len(parts) != 3 or any(p < 0 or p > 255 for p in parts):
                raise ValueError()
            hex_val = f"#{parts[0]:02X}{parts[1]:02X}{parts[2]:02X}"
            self.entry_hex.delete(0, tk.END)
            self.entry_hex.insert(0, hex_val)
            self.result_var.set(f"Hex 结果: {hex_val}")
            self.update_preview(hex_val)
        except Exception:
            messageWarning("输入错误", "请输入有效的 RGB 格式(0-255),例如: 255, 100, 50")

    def hex_to_rgb(self):
        text = self.entry_hex.get().strip().lstrip('#')
        try:
            if len(text) != 6:
                raise ValueError()
            r = int(text[0:2], 16)
            g = int(text[2:4], 16)
            b = int(text[4:6], 16)
            rgb_str = f"{r}, {g}, {b}"
            self.entry_rgb.delete(0, tk.END)
            self.entry_rgb.insert(0, rgb_str)
            self.result_var.set(f"RGB 结果: {rgb_str}")
            self.update_preview(f"#{text}")
        except Exception:
            messageWarning("输入错误", "请输入有效的 6 位 Hex 颜色码,例如: #FF6432")

    def copy_to_clipboard(self):
        res = self.result_var.get()
        if "结果:" in res:
            val = res.split("结果: ")[1]
            self.root.clipboard_clear()
            self.root.clipboard_append(val)
            messagebox.showinfo("成功", f"已复制 '{val}' 到剪贴板!")

def messageWarning(title, msg):
    messagebox.showwarning(title, msg)

if __name__ == "__main__":
    root = tk.Tk()
    app = ColorConverterApp(root)
    root.mainloop()
2. 通用打包脚本:build_exe.py

AI 生成的自动化一键构建流程脚本:

Python

import os
import shutil
import subprocess
import sys

def run_cmd(cmd):
    """运行终端命令"""
    result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
    if result.returncode != 0:
        print(f"❌ 执行失败: {cmd}")
        print(result.stderr)
        sys.exit(1)
    return result.stdout

def build():
    print("🚀 开始 AI 自动化生成 .exe 流程...")

    # 1. 自动检查并安装 PyInstaller
    try:
        import PyInstaller
        print("✓ PyInstaller 已就绪")
    except ImportError:
        print("⚙️ 未检测到 PyInstaller,正在自动安装...")
        run_cmd(f"{sys.executable} -m pip install pyinstaller")

    # 2. 执行打包指令
    target_script = "app.py"
    app_name = "ColorConverter"
    print(f"📦 正在打包 `{target_script}` ...")

    # --onefile: 单一文件 | --noconsole: 隐藏黑窗口
    build_cmd = f"pyinstaller --onefile --noconsole --name={app_name} {target_script}"
    run_cmd(build_cmd)

    # 3. 清理临时打包垃圾文件
    print("🧹 正在清理构建缓存...")
    if os.path.exists("build"):
        shutil.rmtree("build")
    spec_file = f"{app_name}.spec"
    if os.path.exists(spec_file):
        os.remove(spec_file)

    # 4. 输出最终成果路径
    exe_path = os.path.abspath(os.path.join("dist", f"{app_name}.exe"))
    if os.path.exists(exe_path):
        print("\n==========================================")
        print("🎉 构建成功!可执行文件已生成:")
        print(f"👉 {exe_path}")
        print("==========================================\n")
    else:
        print("❌ 打包完成但未找到生成的 .exe 文件,请检查输出。")

if __name__ == "__main__":
    build()

第三步:生成与运行

当你把提示词发给带有 Terminal 执行能力的 AI 工具(例如 CursorClaude CodeWindsurf)时:

  1. AI 智能体会在本地目录创建 app.pybuild_exe.py

  2. AI 会自动触发终端命令:

    Bash

    python build_exe.py
    
  3. 稍等数秒,打包完成后,你便可以在当前的 dist/ 目录下双击直接运行 ColorConverter.exe,无需在目标电脑上安装 Python 或任何依赖项。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值