将NiceGUI应用程序打包成EXE文件

将NiceGUI应用程序打包成EXE文件

NiceGUI是一个简单易用的Python库,用于创建基于文本的用户界面。在本教程中,我们将学习如何将NiceGUI应用程序打包成可执行文件(EXE)。

步骤1:安装依赖项

首先,我们需要确保在打包应用程序之前安装必要的依赖项。在命令行中运行以下命令来安装所需的库:

pip install pyinstaller

步骤2:创建NiceGUI应用程序

接下来,我们需要创建一个NiceGUI应用程序my_login.py。以下是一个简单的示例:

#!/usr/bin/env python3
"""This is just a very simple authentication example.
"""
from fastapi.responses import RedirectResponse

from nicegui import app, ui

# in reality users passwords would obviously need to be hashed
passwords = {
    
    'user1': 'pass1', 'user2': 'pass2'}


@ui.page('/')
def main_page() -> None:
    if not app.storage.user.get('authenticated', False):
        return RedirectResponse('/login')
    with ui.column().classes('absolute-center items-center'):
        ui.label(f'Hello {
      
      app.storage.user["username"]}!').classes('text-2xl')
        ui.button(on_click=lambda: (app.storage.user.clear(), ui.open('/login')), icon='logout').props('outline round')


@ui.page('/login')
def login() -> None:
    def try_login() -> None:  # local function to avoid passing username and password as arguments
        print(passwords.get(username.value))
        if passwords.get(username.value) == password.value:
            app.storage.user.update({
    
    'username': username.value, 'authenticated': True})
            ui.open('/')
        else:
            ui.notify('Wrong username or password', color='negative')

    if app.storage.user.get('authenticated', False):
        return RedirectResponse('/')
    with ui.card().classes('absolute-center'):
        username = ui.input('Username').on('keydown.enter', try_login)
        password = ui.input('Password', password=True, password_toggle_button=True).on('keydown.enter', try_login)
        ui.button('Log in', on_click=try_login)


ui.run(reload=False,native=True,storage_secret='THIS_NEEDS_TO_BE_CHANGED')

在上面的示例中,我们导入了nicegui库并创建了一个简单的NiceGUI应用程序。

在 ui.run 函数中,设置2个参数
reload = False 是打包必需
native = True ,程序启动时,就像普通的程序一样有独立的窗体。如果此参数为False,那么启动时就会触发浏览器打开页面

步骤3:打包应用程序

现在,我们可以使用PyInstaller工具将NiceGUI应用程序打包成EXE文件。然后在同目录下创建一个 build.py 文件,代码如下:

import os
import subprocess
from pathlib import Path
import nicegui
cmd = ['PyInstaller',
'my_login.py',#your main file with ui.run()
'--name','myapp',#name of your app
'--onefile',
'--windowed',
'--clean',
'--add-data',f'{Path(nicegui.__file__).parent}{os.pathsep}nicegui'
]
subprocess.call(cmd)

确保将my_login.py替换为您的NiceGUI应用程序的实际文件名。

--onefile参数将应用程序打包成单个EXE文件,而--windowed参数将应用程序显示为窗口应用程序,而不是命令行应用程序。
执行

python build.py

完成后,您将在同一目录下找到一个名为dist的文件夹,其中包含您的NiceGUI应用程序的EXE文件。
在这里插入图片描述

结论

通过遵循上述步骤,您可以轻松地将NiceGUI应用程序打包成EXE文件,以便在没有Python环境的计算机上运行。这为您的应用程序的分发和共享提供了便利。

猜你喜欢

转载自blog.csdn.net/sinat_35773915/article/details/132562851