吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 3184|回复: 67
收起左侧

[Python 转载] python打包转exe工具

[复制链接]
6khome 发表于 2025-5-7 16:13
本帖最后由 6khome 于 2025-5-7 16:16 编辑

20250507
一个python打包成exe文件的工具
是基于坛友分享的源码做的修改,源链接找不到了,分享给大家


最新下载地址:https://wwqq.lanzoub.com/iFGHX2vlnyzc 密码:52pj


[Asm] 纯文本查看 复制代码
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
import sys
import os
import re
import shutil
from PyQt6.QtWidgets import (QApplication, QMainWindow, QPushButton,
                             QFileDialog, QLabel, QVBoxLayout, QWidget,
                             QProgressBar, QCheckBox, QGroupBox, QGridLayout,
                             QLineEdit)
from PyQt6.QtCore import Qt, QThread, pyqtSignal
from PyQt6.QtGui import QIcon, QFont
import subprocess
 
 
class ConvertThread(QThread):
    progress = pyqtSignal(str)
    finished = pyqtSignal(bool, str)
    stop_flag = False
 
    def __init__(self, file_path, options):
        super().__init__()
        self.file_path = file_path
        self.options = options
        self.stop_flag = False
 
    def run(self):
        if self.stop_flag:
            return
        try:
            script_dir = os.path.dirname(os.path.abspath(self.file_path))
            dist_dir = os.path.join(script_dir, 'dist')
 
            command = ['pyinstaller']
 
            if self.options['onefile']:
                command.append('--onefile')
            else:
                command.append('--onedir')
 
            if self.options['noconsole']:
                command.append('--noconsole')
                command.append('--windowed')
 
            command.extend(['--clean'])
 
            command.extend(['--distpath', dist_dir])
            command.extend(['--specpath', script_dir])
            command.extend(['--workpath', os.path.join(script_dir, 'build')])
 
            images_dir = os.path.join(script_dir, 'images')
            if os.path.exists(images_dir):
                if os.name == 'nt':
                    command.extend(['--add-data', f'{images_dir};images'])
                else:
                    command.extend(['--add-data', f'{images_dir}:images'])
 
            if self.options['icon'] and os.path.exists(self.options['icon']):
                command.extend(['--icon', self.options['icon']])
 
            if self.options['name']:
                if re.match(r'^[a-zA-Z0-9_\-.\u4e00-\u9fa5][a-zA-Z0-9_\-.\u4e00-\u9fa5 ]*$', self.options['name']):
                    command.extend(['--name', self.options['name']])
                else:
                    self.finished.emit(False, "程序名称包含非法字符或格式不正确!")
                    return
 
            command.append(self.file_path)
 
            self.progress.emit(f"执行命令: {' '.join(command)}")
 
            try:
                result = subprocess.run(
                    command,
                    capture_output=True,
                    text=True,
                    check=True
                )
            except FileNotFoundError:
                error_msg = "未找到 pyinstaller 程序,请确保已正确安装!"
                self.progress.emit(error_msg)
                self.finished.emit(False, error_msg)
                return
            except subprocess.CalledProcessError as e:
                error_msg = f"返回码: {e.returncode}, 错误输出: {e.stderr or '未知错误'}"
                self.progress.emit(f"错误输出: {error_msg}")
                self.finished.emit(False, f"转换失败: {error_msg}")
                return
            except Exception as e:
                error_msg = f"发生未知错误: {str(e)}"
                self.progress.emit(error_msg)
                self.finished.emit(False, error_msg)
                return
 
            if result.returncode == 0:
                output_dir = dist_dir
                output_name = self.options['name'] if self.options['name'] else \
                    os.path.splitext(os.path.basename(self.file_path))[0]
                output_ext = '.exe' if self.options['onefile'] else ''
                output_path = os.path.join(output_dir, f'{output_name}{output_ext}')
 
                # 转换成功后,删除 build 目录
                build_dir = os.path.join(script_dir, 'build')
                if os.path.exists(build_dir):
                    try:
                        shutil.rmtree(build_dir)
                        self.progress.emit(f"已删除 build 目录: {build_dir}")
                    except Exception as e:
                        self.progress.emit(f"删除 build 目录时出错: {str(e)}")
 
                self.finished.emit(True, f"转换成功!请查看 {output_path}")
            else:
                error_msg = result.stderr or "未知错误"
                self.progress.emit(f"错误输出: {error_msg}")
                self.finished.emit(False, f"转换失败: {error_msg}")
 
        except Exception as e:
            error_msg = f"发生未知错误: {str(e)}"
            self.progress.emit(error_msg)
            self.finished.emit(False, error_msg)
 
    def stop(self):
        self.stop_flag = True
 
 
class Py2ExeConverter(QMainWindow):
    def __init__(self):
        super().__init__()
        base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
        icon_path = os.path.join(base_path, 'images', '64.ico')
        try:
            self.setWindowIcon(QIcon(icon_path))
        except Exception:
            print("图标文件未找到或格式不正确。")
        self.init_ui()
 
    def init_ui(self):
        self.setWindowTitle("Python打包转EXE工具")
        self.setFixedSize(600, 400)
 
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
 
        layout = QVBoxLayout()
 
        file_group = self.create_file_selection_group()
        layout.addWidget(file_group)
 
        options_group = self.create_options_group()
        layout.addWidget(options_group)
 
        self.progress_label = QLabel("准备就绪")
        self.progress_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.progress_label.setWordWrap(True)
        self.progress_bar = QProgressBar()
        self.progress_bar.setTextVisible(False)
 
        self.convert_button = QPushButton("开始转换")
        self.convert_button.setStyleSheet("""
            QPushButton {
                background-color: #2196F3;
                color: white;
                padding: 8px;
                font-weight: bold;
                border-radius: 4px;
            }
            QPushButton:hover {
                background-color: #1976D2;
            }
        """)
 
        layout.addWidget(self.progress_label)
        layout.addWidget(self.progress_bar)
        layout.addWidget(self.convert_button)
 
        main_widget.setLayout(layout)
 
        self.convert_button.clicked.connect(self.convert_to_exe)
 
        self.selected_file = None
        self.convert_thread = None
 
    def create_file_selection_group(self):
        file_group = QGroupBox("文件选择")
        file_layout = QGridLayout()
 
        self.file_label = QLabel("未选择文件")
        self.file_label.setStyleSheet("background-color: #f0f0f0; border-radius: 3px;")
        select_button = QPushButton("选择 Python 文件")
        select_button.setFixedSize(260, 28)
        select_button.setStyleSheet("background-color: #4CAF50; color: white; padding: 5px;")
 
        file_layout.addWidget(self.file_label, 0, 0)
        file_layout.addWidget(select_button, 0, 1)
        file_group.setLayout(file_layout)
 
        select_button.clicked.connect(self.select_file)
        return file_group
 
    def create_options_group(self):
        options_group = QGroupBox("转换选项")
        options_layout = QGridLayout()
 
        self.onefile_check = QCheckBox("生成单个文件")
        self.onefile_check.setChecked(True)
        self.noconsole_check = QCheckBox("隐藏控制台窗口")
        self.noconsole_check.setChecked(True)
 
        self.icon_label = QLabel("图标文件(.ico):")
        self.icon_path = QLineEdit()
        self.icon_path.setPlaceholderText("可选:选择ico格式图片")
        icon_button = QPushButton("上传")
        icon_button.clicked.connect(self.select_icon)
 
        self.name_label = QLabel("程序名称(.exe):")
        self.name_input = QLineEdit()
        self.name_input.setPlaceholderText("可选:指定输出exe名称")
 
        options_layout.addWidget(self.onefile_check, 0, 0)
        options_layout.addWidget(self.noconsole_check, 0, 1)
        options_layout.addWidget(self.icon_label, 1, 0)
        options_layout.addWidget(self.icon_path, 1, 1)
        options_layout.addWidget(icon_button, 1, 2)
        options_layout.addWidget(self.name_label, 2, 0)
        options_layout.addWidget(self.name_input, 2, 1)
        options_group.setLayout(options_layout)
 
        return options_group
 
    def select_file(self):
        file_name, _ = QFileDialog.getOpenFileName(
            self,
            "选择 Python 文件",
            "",
            "Python Files (*.py)"
        )
        if file_name:
            if not os.path.exists(file_name):
                self.progress_label.setText("选择的 Python 文件不存在!")
                return
            self.selected_file = file_name
            self.file_label.setText(f"已选择: {os.path.basename(file_name)}")
            default_name = os.path.splitext(os.path.basename(file_name))[0]
            self.name_input.setText(default_name)
 
    def select_icon(self):
        icon_path, _ = QFileDialog.getOpenFileName(
            self,
            "选择图标文件",
            "",
            "Icon Files (*.ico)"
        )
        if icon_path:
            if not os.path.exists(icon_path):
                self.progress_label.setText("选择的图标文件不存在!")
                return
            script_dir = os.path.dirname(os.path.abspath(self.selected_file))
            images_dir = os.path.join(script_dir, 'images')
            if not os.path.exists(images_dir):
                os.makedirs(images_dir)
            icon_filename = os.path.basename(icon_path)
            target_path = os.path.join(images_dir, icon_filename)
            try:
                shutil.copy2(icon_path, target_path)
                self.icon_path.setText(target_path)
                self.progress_label.setText(f"图标文件已复制到 {target_path}")
            except Exception as e:
                self.progress_label.setText(f"复制图标文件时出错: {str(e)}")
 
    def update_progress(self, message):
        self.progress_label.setText(message)
        self.progress_bar.setMaximum(0)
 
    def conversion_complete(self, success, message):
        self.convert_button.setEnabled(True)
 
        self.progress_bar.setMaximum(100)
        self.progress_bar.setValue(100 if success else 0)
        self.progress_label.setText(message)
 
    def convert_to_exe(self):
        if not self.selected_file:
            self.progress_label.setText("请先选择 Python 文件!")
            return
 
        self.convert_button.setEnabled(False)
        self.progress_label.setText("正在转换中...")
        self.progress_bar.setMaximum(0)
 
        options = {
            'onefile': self.onefile_check.isChecked(),
            'noconsole': self.noconsole_check.isChecked(),
            'icon': self.icon_path.text(),
            'name': self.name_input.text().strip()
        }
 
        self.convert_thread = ConvertThread(self.selected_file, options)
        self.convert_thread.progress.connect(self.update_progress)
        self.convert_thread.finished.connect(self.conversion_complete)
        self.convert_thread.start()
 
    def closeEvent(self, event):
        if self.convert_thread and self.convert_thread.isRunning():
            self.convert_thread.stop()
            self.convert_thread.wait()
        event.accept()
 
 
if __name__ == '__main__':
    app = QApplication(sys.argv)
 
    app.setStyle('Fusion')
 
    window = Py2ExeConverter()
    window.show()
    sys.exit(app.exec())





界面截图

界面截图

免费评分

参与人数 8吾爱币 +7 热心值 +5 收起 理由
wananyu + 1 + 1 用心讨论,共获提升!
darksky2015 + 1 谢谢@Thanks!
dexi_pj + 1 谢谢@Thanks!
joeuv + 1 热心回复!
小兔一样的小白 + 1 + 1 热心回复!
快乐的小驹 + 1 + 1 非常好~唯一缺点不能移动exe的位置~移动了就没有图标了!
At作梦 + 1 热心回复!
xk1539287520 + 1 + 1 谢谢@Thanks!

查看全部评分

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

wang1098 发表于 2025-5-7 16:37
一直没弄明白怎么自己打包总不成功,里面用到的图片文件还需要与exe文件放到同一目录下才行,可是明明选择了打包成单个文件
307921917 发表于 2025-5-7 16:39
一场荒唐半生梦 发表于 2025-5-7 16:23
Pwaerm 发表于 2025-5-7 16:39
wang1098 发表于 2025-5-7 16:37
一直没弄明白怎么自己打包总不成功,里面用到的图片文件还需要与exe文件放到同一目录下才行,可是明明选择 ...

默认不会把需要引用的资源打包进去,需要在 .spec的datas=[]参数里面指定
samdong 发表于 2025-5-7 16:24
我的怎么打包时间要好久啊
qqjgx 发表于 2025-5-7 16:31
之前有坛友发布一个py转exe的,能自动下载需要的依赖文件,不知道贴主这个是否可以。
wang1098 发表于 2025-5-7 16:41
Pwaerm 发表于 2025-5-7 16:39
默认不会把需要引用的资源打包进去,需要在 .spec的datas=[]参数里面指定

指定了相对路径
jun269 发表于 2025-5-7 16:45
一些相关联的文件能不能自己判断,一起打包呢?
fuvenusck 发表于 2025-5-7 16:49
转换很丝滑,工具很实用,谢谢分享
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

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

GMT+8, 2025-6-1 23:55

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

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