You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Py2app打包Tkinter应用启动提示Paattajahaku意外退出求助

问题描述

接触Python时间较短,这是开发的首个应用。程序代码在终端、PyCharm环境下运行均正常,但使用Py2app完成打包后,启动生成的Paattajahaku.app文件时,系统弹出*Paattajahaku quit unexpectedly.(Paattajahaku意外退出)*报错,无法正常运行,不清楚故障原因,完整代码如下:

import tkinter as tk
from tkinter import ttk
from tkinter import filedialog as fd
from bs4 import BeautifulSoup as bs
import requests
import pandas as pd
from time import sleep
from random import randint

root = tk.Tk()
root.title("Tkinter open file dialog")
root.resizable(False, False)
root.geometry("300x150")

titleslist = []
nameslist = []
fonrlist = []
df = pd.DataFrame(titleslist)


def select_file():
    filetypes = (
        ("text files", "*txt",
         "excel files", "*xlsx")
    )

    filename = fd.askopenfile(
        title="open a file",
        initialdir="/",
        )
    print("Please wait...")
    for files in filename:
        newfo_nr = files.strip().zfill(8)
        fonrlist.append(newfo_nr)
        sleep(randint(2, 4))  # sleep for a random time
        url = f"https://www.asiakastieto.fi/yritykset/fi/{newfo_nr}/paattajat"
        page = requests.get(url)
        soup = bs(page.content, "html.parser")
        names = soup.find_all(attrs={"data-title": "Nimi"})
        titles = soup.find_all(attrs={"data-title": "Asema"})
        for title in titles:
            titleslist.append(title.text)
            for name in names:
                nameslist.append(name.text)
                number_of_names = len(nameslist)
                number_of_fo_nr = len(fonrlist)
                sumfo = number_of_names - number_of_fo_nr
                for i in range(sumfo):
                    if i < sumfo:
                        fonrlist.append(newfo_nr.strip())
                        if title == " ":
                            break
                else:
                    continue
                break
            else:
                continue
            break
        else:
            continue
        break
    print("Files saved")
    df = pd.DataFrame(list(zip(fonrlist, titleslist, nameslist))) # works

    try:
        # with block automatically closes file
        with fd.asksaveasfile(mode='w', defaultextension=".xlsx") as file:
            df.to_excel(file.name)
    except AttributeError:
        # if user cancels save, filedialog returns None rather than a file object, and the 'with' will raise an error
        print("The user cancelled save")


def saveFile():
    try:
        # with block automatically closes file
        with fd.asksaveasfile(mode='w', defaultextension=".xlsx") as file:
            df.to_excel(file.name, index=False, header=False)
    except AttributeError:
        # if user cancels save, filedialog returns None rather than a file object, and the 'with' will raise an error
        print("The user cancelled save")


open_button = ttk.Button(
    root,
    text="Open a file",
    command=select_file
)
exit_button = ttk.Button(
    root,
    text="Exit",
    command=root.destroy
)
open_button.pack(expand=True)
exit_button.pack(expand=True)
root.mainloop()
故障排查与修复
  • Py2app打包默认不会自动收集所有第三方依赖的隐式导入,代码中用到的bs4、requests、pandas,以及pandas导出xlsx必需的依赖openpyxl,如果没有在打包配置中显式声明,打包后的程序会因为缺模块直接崩溃。
  • 修正打包配置:
    打包使用的setup.py需要补全包依赖声明,参考配置:
    from setuptools import setup
    
    APP = ['主程序文件名.py']
    DATA_FILES = []
    OPTIONS = {
        'argv_emulation': True,
        'packages': ['bs4', 'requests', 'pandas', 'openpyxl'],
    }
    
    setup(
        app=APP,
        data_files=DATA_FILES,
        options={'py2app': OPTIONS},
        setup_requires=['py2app'],
    )
    
    配置完成后重新执行打包命令python setup.py py2app即可。
  • 定位具体报错:不要直接双击启动app,打开终端进入app包内的执行文件目录,直接运行二进制文件就能看到完整崩溃日志,执行命令:
    ./dist/Paattajahaku.app/Contents/MacOS/Paattajahaku
    
    终端输出的内容会直接标明缺失模块、路径错误、权限问题等具体故障点。
  • 代码本身问题修复:
    • 文件选择器的filetypes参数写法错误,每个文件类型规则需要单独写成二元组,原写法无法正常筛选文件,修正为:
      filetypes = (
          ("text files", "*.txt"),
          ("excel files", "*.xlsx")
      )
      
    • 导出xlsx功能依赖openpyxl库,本地环境先执行pip install openpyxl完成安装,否则代码运行时也会报错。

内容的提问来源于stack exchange,提问作者32kode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 01:24:20