我創建了一個 GUI,它加載了一個my_lib依賴于許多重型模塊的庫。它將使用 PyInstaller 轉換為可執行檔案。
我想創建一個啟影片面來隱藏較長(超過 5 秒)的加載時間。
一種方法是使用--splashPyInstaller 的引數,但這將獨立于程式并使用計時器作業。
另一種方法是使用 PyQt5 創建啟影片面。這是主腳本的示例:
# various imports including standard library and PyQt.
from my_lib import foo, bar, docs_url, repo_url
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.action_docs.triggered.connect(lambda x: QDesktopServices.openUrl(QUrl(docs_url)))
self.action_code.triggered.connect(lambda x: QDesktopServices.openUrl(QUrl(repo_url)))
def show_splash(self):
self.splash = QSplashScreen(QPixmap("path\to\splash.png"))
self.splash.show()
# Simple timer to be replaced with better logic.
QTimer.singleShot(2000, self.splash.close)
if __name__ == '__main__':
app = QApplication(sys.argv)
app.setStyle(QStyleFactory.create('fusion'))
main = MainWindow()
main.show()
main.show_splash()
sys.exit(app.exec_())
上面代碼的問題是匯入是在頂部完成的,然后打開了啟動螢屏,這與這一點無關。此外,MainWindow類的定義取決于從my_lib.
How can I hide the loading time of the heavy modules when the basic definitions of the GUI depends on them? Is there I'm something missing? Is it even possible?
uj5u.com熱心網友回復:
編輯:這種方法是不必要的。正如@musicamante 在評論中指出的那樣,上述(已編輯)示例沒有引發任何錯誤,并且可以毫無問題地使用。
在考慮了@musicamante 的評論后,我想到將 __ main __ 條件中的邏輯分為兩部分。一個在重進口之前,另一個在最后。所以它是這樣的:
if __name__ == '__main__':
app = QApplication(sys.argv)
app.setStyle(QStyleFactory.create('fusion'))
splash_object = QSplashScreen(QPixmap("path\to\splash.png"))
splash_object.show()
#
# Load the heavy libraries, including my_lib.
#
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
if __name__ == '__main__':
splash_object.close()
main = MainWindow()
main.show()
sys.exit(app.exec_())
這似乎作業得很好,但我不確定這種分裂的任何副作用。
應該注意的是,大部分啟動時間似乎來自于對可執行檔案的解包。
編輯:這個答案提出了類似的方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/456507.html
標籤:python user-interface pyqt5 pyinstaller
上一篇:如何正確使用鍵盤系結?
