我已经用Kivy制作了一些东西,这是核心代码:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder
class UI(Widget):
pass
class UIApp(App):
def build(self):
Window.bind(on_key_down=self.key_action)
return UI()
def key_action(self, *args):
self.process()
def on_start(self, **kwargs):
pass
def on_stop(self):
raise SystemExit(0)
def process(self):
OtherFile.test()
if __name__ == "__main__":
Builder.load_file('UI.kv')
from kivy.core.window import Window
UIApp().run()
如您所见,我需要导入窗口以获取键盘钩。
OtherFile.test()但是使用多线程。发生这种情况时,会立即弹出新的Kivy窗口。但是,只有当我将脚本打包到exe中时,脚本正常执行时,才会发生这种情况。我遵循了this guide,并具有以下规格文件:
# -*- mode: python -*-
import sys
from os import path
site_packages = next(p for p in sys.path if 'site-packages' in p)
from kivy.deps import sdl2, glew
block_cipher = None
a = Analysis(['Main.py'],
pathex=['C:\\Users\\GFuel\\PycharmProjects\\proj'],
binaries=[],
datas=[],
hiddenimports=[],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
[],
exclude_binaries=True,
name='AppName',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
console=True )
coll = COLLECT(exe, Tree('C:\\Users\\GFuel\\PycharmProjects\\proj'),
a.binaries,
a.zipfiles,
a.datas,
*[Tree(p) for p in (sdl2.dep_bins + glew.dep_bins)],
strip=False,
upx=True,
name='AppName')
我使用PyInstaller AppName.spec -windowed -singlefile
进行编译。窗口本身可以正常工作:
[INFO ] [Window ] auto add sdl2 input provider
[INFO ] [Window ] virtual keyboard not allowed, single mode, not docked
[INFO ] [Text ] Provider: sdl2
[INFO ] [GL ] NPOT texture support is available
[INFO ] [Base ] Start application main loop
但是,一旦我按下一个键,就会有越来越多的窗口开始打开。我的猜测是出于某种原因,__name__
是__main__
,即使由于PyInstaller而不应该(在多处理过程中),但我不知道如何解决它。
编辑:我已经通过以下方法证明了这一点:
if __name__ == "__main__":
print("YAY")
from kivy.lang import Builder
from kivy.core.window import Window
Builder.load_file('UI.kv')
UIApp().run()
在我按下一个键后,YAY出现了几次。简而言之,有没有办法使打包的脚本正常工作?
答案 0 :(得分:0)
if __name__ == "__main__":
multiprocessing.freeze_support()
这些必须是在主脚本中运行的第一行。该脚本仍会使用所有应有的线程,但可与exe一起正常使用。