基于单选框输入实现Python文件动态导入与页面跳转的问题
问题:通过单选框动态导入Python文件并跳转页面
我希望通过单选框获取用户输入,以此动态导入指定Python文件并跳转到对应页面,但目前无法获取用户更新后的选择来完成导入与跳转操作。
示例文件:
- scriptA.py:
class A: def __init__(self, a): self.a = a
- scriptB.py:
class B: def __init__(self, b): self.b = b
我的实现代码(app.py):
class ImportSelection: def __init__(self, selection = None): self.selection = selection importselection = ImportSelection() ui.radio(['A', 'B']).bind_value(importselection, 'selection') @ui.page('/A') def page_A(): from scriptA import A # do stuff @ui.page('/B') def page_B(): from scriptB import B # do stuff if importselection.selection == 'A': ui.link("/A", page_A) elif importselection.selection == 'B': ui.link("/B", page_B) ui.run()
请问应如何重构这段代码以实现需求?
解决方案
你的代码核心问题在于初始化阶段就执行了选择判断,此时用户还未进行任何选择,且没有监听单选框的变化事件。可以通过绑定单选框的on_change回调函数,结合页面导航和动态导入来实现需求。
重构后的代码如下:
import importlib from nicegui import ui class ImportSelection: def __init__(self, selection=None): self.selection = selection importselection = ImportSelection() def handle_selection_change(): selected = importselection.selection if not selected: return # 动态导入对应模块(可选,若仅在页面内使用可跳过此部分) module = importlib.import_module(f'script{selected}') target_class = getattr(module, selected) # 这里可以提前对类做初始化或其他操作,比如: # instance = target_class('default_value') # 跳转到对应页面 ui.navigate.to(f'/{selected}') # 首页展示单选框 @ui.page('/') def index_page(): ui.label('请选择要导入的模块:') # 绑定单选框值到实例,并监听变化事件 ui.radio(['A', 'B']).bind_value(importselection, 'selection').on('change', handle_selection_change) @ui.page('/A') def page_A(): from scriptA import A ui.label('已进入页面A') # 在此处使用A类完成业务逻辑 example_instance = A('test_a') ui.label(f"A类实例的属性值:{example_instance.a}") @ui.page('/B') def page_B(): from scriptB import B ui.label('已进入页面B') example_instance = B('test_b') ui.label(f"B类实例的属性值:{example_instance.b}") ui.run()
关键修改说明:
- 新增
handle_selection_change回调函数:监听单选框的选择变化,一旦用户选择选项,立即执行动态导入和页面跳转 - 使用
ui.navigate.to()实现自动跳转:替代原代码中静态创建链接的方式,实现选择后直接跳转到目标页面 - 动态导入优化:通过
importlib模块根据选择动态导入对应文件,若仅在目标页面内使用类,也可保留页面内的静态导入 - 新增首页
/:确保用户打开应用时能看到单选框进行选择,原代码缺少初始页面会导致界面空白
内容的提问来源于stack exchange,提问作者cjk5642
相关产品推荐
相关产品推荐

