我无法将我的 py 文件打包为 exe 文件

我对编程非常陌生,我决定使用 python 作为我的第一个编程语言!所以我通过 Pygame 创建了一个没有附加文件的游戏,它只是一个 python 文件。

这只是一个问答游戏,我通过代码本身创建了一个 GUI。使用 cmd 运行游戏时,游戏运行得很好,但是当我使用 pyinstaller 将其转换为可执行文件并尝试运行它时,它只会闪烁一个空窗口黑屏,然后关闭。我什至尝试使用 cx freeze 。我尝试了很多解决方案,但没有一个有效。任何帮助,将不胜感激。我对编程很陌生,所以如果你能回答我的问题,你能用初学者的话解释一下吗哈哈哈。这是我的游戏的代码:

import random 

from random import randint


WIDTH = 1280


HEIGHT = 720


def draw():

    screen.fill("green yellow")

    screen.draw.filled_rect(main_box, "sky blue")

    screen.draw.filled_rect(timer_box, "sky blue")

    screen.draw.text("Score: " + str(score), color="black", topleft=(10, 10))


    for box in answer_boxes:

        screen.draw.filled_rect(box, "orange")


    screen.draw.textbox(str(time_left), timer_box, color=('black'))

    screen.draw.textbox(question[0], main_box, color=('black'))


    index = 1

    for box in answer_boxes:

        screen.draw.textbox(question[index], box, color=('black'))

        index = index + 1


def game_over():

    global question, time_left, scoredecreaserps

    scoredecreaserps = 0

    message = 'Game Over. You got %s questions correct' %str(numques)

    question = [message, '-', '-', '-', '-', 5]

    time_left = 0


def correct_answer():

    global question, score, numques, time_left


    numques = numques + 1

    score = score + 1000


    if questions:

        question = questions.pop()

        time_left = 10

    else:

        print('End of questions')

        game_over()


def on_mouse_down(pos):

    index = 1


    for box in answer_boxes:


        if box.collidepoint(pos):

            print('Clicked on answer' + str(index))


            if index == question[5]:

                print('You got it correct!')

                correct_answer()

            else:

                game_over()


        index = index + 1


def update_time_left():

    global time_left


    if time_left:

        time_left = time_left - 1

    else:

        game_over()


def score_lower():

    global score


    if score:

        score = score - scoredecreaserps


main_box = Rect(50, 40, 820, 240)

timer_box = Rect(990, 40, 240, 240)



长风秋雁
浏览 40回答 3
3回答

一只名叫tom的猫

如果您是编程新手,则不应专注于创建二进制文件。通过学习面向对象编程、函数式编程以及每种代码方法的优缺点,了解如何在 shell 中运行应用程序并培养一些开发人员技能。您将意识到大多数项目不需要 exe 来运行它。如果您希望文件单击并运行,您可以使用某些 Windows 配置直接运行 python 文件*,或者创建一个 shell 脚本来设置和/或运行它。这种方法是使用 python 的更自然的方式。* 我很长时间不使用 Windows,但我相信您可以从 UI 中使用 python.exe 打开 python 文件。

明月笑刀无情

我已经成功解决了您的任务,请执行后续步骤:必要的模块需要一次性安装:python -m pip install pyinstaller pgzero requestsgame.zip通过运行下一个命令行来检索包含所有所需资源的存档:python -c "import requests, base64; f = open('game.zip', 'wb'); f.write(base64.b64decode(requests.get('https://pastebin.com/raw/GnJ72zgP').content)); f.close()"文件内部game.zip已经有所需的一切,只需package.cmd在那里运行,打包后花费一些时间,您将获得dist/script.exe.game.zip有下一个文件:package.cmd包含一行pyinstaller --noconfirm --onefile --console --noupx --add-data "./pgzero/;./pgzero/" --add-data "./fonts/;./fonts/" --runtime-tmpdir "c:/temp/" script.pyscript.py包含我将在下面提供的完整脚本代码。fonts/arial.ttf包含取自的文件C:\Windows\Fonts\arial.ttf。pgzero/data/等于文件夹D:\bin2\Python37\Lib\site-packages\pgzero\data\(在此路径中更改 Python 发行版的位置)。完整更正和改进的脚本代码如下。您可能需要更改第一行 - 变量logname等于写入日志的路径,如果程序崩溃,所有异常都会写在那里,变量等于fontname位于 中的字体的文件名,您可以将此字体替换为您喜欢的字体。./fonts/arial.ttfgame.zip脚本可以通过python script.py命令运行,也可以通过将其打包到script.exeusing中来运行pyinstaller。接下来进行了改进:添加try/except全局块是为了捕获所有程序的异常/错误,内部except块错误将保存到带有logname变量路径的日志文件中。添加faulthandler到脚本的第一行,以捕获所有严重错误,例如Segmentation Fault.在第一行中添加os.chdir(...),将工作目录更改为运行打包脚本的目录。因为默认情况下打包脚本的工作目录不等于脚本所在的目录。添加import pgzrun在第一行和pgzrun.go()最后一行中,这使得脚本可以仅通过python script.py而不是脚本运行pgzrun script.py常见的命令行来运行pygame。为了允许使用 pyinstaller 轻松打包,此改进是必要的。fontname = fontname为所有函数调用添加了参数screen.draw.text...(...),因为如果未给出字体文件名,打包脚本将崩溃。try:    logname = 'c:/temp/pgzrun.log'    fontname = 'arial.ttf'    import faulthandler    faulthandler.enable()        import os, sys        script_dir = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))    os.chdir(script_dir)        import pgzrun        import random     from random import randint    WIDTH = 1280    HEIGHT = 720    def draw():        screen.fill("green yellow")        screen.draw.filled_rect(main_box, "sky blue")        screen.draw.filled_rect(timer_box, "sky blue")        screen.draw.text("Score: " + str(score), color="black", topleft=(10, 10), fontname=fontname)        for box in answer_boxes:            screen.draw.filled_rect(box, "orange")        screen.draw.textbox(str(time_left), timer_box, color=('black'), fontname=fontname)        screen.draw.textbox(question[0], main_box, color=('black'), fontname=fontname)        index = 1        for box in answer_boxes:            screen.draw.textbox(question[index], box, color=('black'), fontname=fontname)            index = index + 1    def game_over():        global question, time_left, scoredecreaserps        scoredecreaserps = 0        message = 'Game Over. You got %s questions correct' %str(numques)        question = [message, '-', '-', '-', '-', 5]        time_left = 0    def correct_answer():        global question, score, numques, time_left        numques = numques + 1        score = score + 1000        if questions:            question = questions.pop()            time_left = 10        else:            print('End of questions')            game_over()    def on_mouse_down(pos):        index = 1        for box in answer_boxes:            if box.collidepoint(pos):                print('Clicked on answer' + str(index))                if index == question[5]:                    print('You got it correct!')                    correct_answer()                else:                    game_over()            index = index + 1    def update_time_left():        global time_left        if time_left:            time_left = time_left - 1        else:            game_over()    def score_lower():        global score        if score:            score = score - scoredecreaserps    main_box = Rect(50, 40, 820, 240)    timer_box = Rect(990, 40, 240, 240)    answer_box1 = Rect(50, 358, 495, 165)    answer_box2 = Rect(735, 358, 495, 165)    answer_box3 = Rect(50, 538, 495, 165)    answer_box4 = Rect(735, 538, 495, 165)    answer_boxes = [answer_box1, answer_box2, answer_box3, answer_box4]    scoredecreaserps = 80    numques = 0    score = 0    time_left = 10    q1 = ["Who was the third president of the Philippines?",          'Rodrigo Duterte', 'Ramon Magsaysay', 'Jose P. Laurel',          'Fidel V. Ramos', 3]    q2 = ['When was the Philippines granted independece from the US?'          , '1977', '1946', '1935', '1907', 2]    q3 = ['When was the Philippines colonized by Spain', '1898', '1523', '1654',          '1521', 4]    questions = [q1, q2, q3]    random.shuffle(questions)    question = questions.pop(0)    clock.schedule_interval(update_time_left, 1.0)    clock.schedule_interval(score_lower, 1.0)    pgzrun.go()        except:    import traceback    with open(logname, 'a', encoding = 'utf-8') as f:        f.write(''.join(traceback.format_exc()) + '\n')

一只甜甜圈

我在这种情况下使用 auto-py-to-exe https://pypi.org/project/auto-py-to-exe/我的系统:Windows 8.1 上的 Python 2.7 人们告诉我,该 exe 在 Linux + Wine 上也能很好地工作
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python