如何在没有打开控制台窗口的情况下运行Python脚本?

时间:2015-07-07 14:43:10

标签: python tkinter

我想双击我的Python脚本(使用Tkinter GUI),我只想让它打开Tkinter窗口,而不是控制台窗口。

为此,我将扩展名从.py更改为.pyw,这似乎在Windows上正常工作但是当我在Linux机器上双击我的.pyw文件时,它不起作用。它只是冻结了,我不得不重启我的系统。

请建议一个独立于平台的解决方案,它可以帮助我在不打开终端/命令提示符的情况下运行Python脚本。

2 个答案:

答案 0 :(得分:2)

自从我尝试使用linux以来已经有一段时间了,但我相信它应该相当简单,首先你需要在脚本的顶部放一个shebang,这样你的shell就知道要使用哪个可执行文件:

#!/usr/bin/python

或者如果您想要特定版本,可以将其扩展为:

#!/usr/bin/python3.2

使用您想要的任何版本(仅适用于前2位数字)

然后你需要将它标记为可执行文件:

chmod 711 myfile.py

有关详细信息,请参阅此page

然后当你双击它时,在rpi(最后我使用的是linux)上,它会询问你是否要执行它,或者在终端中执行它。

如果您选择在没有终端的情况下执行它,您应该只看到tkinter GUI

答案 1 :(得分:1)

您可以使用pyinstaller为所需的不同平台创建可执行文件。

例如,

pyinstaller命令的语法是:

pyinstaller [options] script [script ...] | specfile

在最简单的情况下,将当前目录设置为程序myscript.py的位置并执行:

pyinstaller myscript.py

PyInstaller分析myscript.py和:

Writes myscript.spec in the same folder as the script.
Creates a folder build in the same folder as the script if it does not exist.
Writes some log files and working files in the build folder.
Creates a folder dist in the same folder as the script if it does not exist.
Writes the myscript executable folder in the dist folder.

在dist文件夹中,您可以找到分发给用户的捆绑应用。

通常,您在命令行上命名一个脚本。如果您更多名称,则会对所有内容进行分析并将其包含在输出中但是,名为的第一个脚本提供spec文件的名称以及可执行文件夹或文件的名称。它的代码是第一个在运行时执行的代码。

对于某些用途,您可以编辑myscript.spec的内容(在使用规范文件中描述)。执行此操作后,将spec文件命名为PyInstaller而不是脚本:

pyinstaller myscript.spec

您可以提供脚本或spec文件的路径,例如

pyinstaller options... ~/myproject/source/myscript.py

或者,在Windows上,

pyinstaller "C:\Documents and Settings\project\myscript.spec"

pyinstaller