将包含 mp3 歌曲的 python 文件转换为可执行文件

Convert python file that contains mp3 song into executable

所以我正在尝试使用 pyinstaller 将 tkinter 文件转换为可执行文件。我已经用图片完成了,但是当我创建包含某种音频的可执行文件时,它说“无法执行脚本 playmusic”(playmusic 是脚本名称)。我试过更改脚本名称,使用 .wav 歌曲,将 dist 文件夹中的 exe 与歌曲一起替换到脚本目录,但 none 有效。我也尝试过使用 auto-py-to-exe,但它不起作用。这首歌是用 pygame 播放的,并且在 VS Code 中没有任何问题。我使用的是 pyinstaller 还是其他模块并不重要。我在 Windows 10.

上使用 python 3.8.2

这是 python 脚本:

import tkinter as tk
from pygame import mixer, time

root = tk.Tk()
root.title("Music Player")
root.geometry("300x100+800+100")

label1=tk.Label(root, text="Start Song: ", fg='green', anchor="w")
label1.grid(row=0, column=0)

file = 'Ignite.mp3'
mixer.init()
mixer.music.load(file)

play = lambda: mixer.music.play()
button1 = tk.Button(root, text = 'Play', command = play)
while mixer.music.get_busy(): time.Clock().tick(10)
button1.grid(row=0, column=2)

pause = lambda: mixer.music.pause()
button2 = tk.Button(root, text="Pause", command = pause)
button2.grid(row=0, column=3)

resume = lambda: mixer.music.unpause()
button3 = tk.Button(root, text="Resume", command = resume)
button3.grid(row=0, column=4)

stop = lambda: mixer.music.stop()
button4 = tk.Button(root, text="Stop", command=stop)
button4.grid(row=0, column=5)

root.mainloop()

这是一种音乐播放器。 我运行执行脚本的pyinstaller代码如下:

pyinstaller --add-data "Ignite.mp3;." --onefile -w playmusic.py

它执行没有问题,但是当我 运行 执行脚本时,在弹出窗口 window 中显示 “无法执行脚本播放音乐”

文件必须位于同一目录中才能正确执行脚本。

如果您在脚本中说:

file = 'Ignite.mp3'
mixer.music.load(file)

并且如果该文件不是您的同一个目录(与您的脚本)。它会在 python 脚本中引发错误,因此也会在您的 exe 中引发错误。

或者您可以说类似绝对路径的内容:

file = 'C:\somefolder\some_more_folder\Ignite.mp3'
mixer.music.load()

但是做成exe发布给某些人推荐第一种方法,所以你需要一个安装文件,所以绝对路径是行不通的,因为它只是你电脑上的路径。但是ypu可以指定安装到程序文件的位置,仍然可以找到方法,但建议使用第一种方法。

所以在确定之后你可以用pyinstaller代码制作一个exe:

pyinstaller -F -w playmusic.py 

希望对您有所帮助,如果还有错误请告诉我。

干杯