You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kivy按钮释放事件的函数作用域问题求助(控件树场景)

问题诊断与修复方案

嘿,我一眼就瞅出问题所在了——你找错了函数的归属对象,导致程序触发未捕获的错误直接崩溃!

核心问题

你的func_authentication方法是定义在SivaLoginScreen这个屏幕类里的,但在kv文件里,你给第二个按钮写的是on_release: app.root.func_authentication()——而app.root是SivaScreenManager(屏幕管理器),它根本没有这个方法,Python找不到方法就会抛出AttributeError,Kivy遇到这种未处理的错误就会直接关掉窗口。

两种快速修复方式

方式1:直接调用当前屏幕的方法(推荐)

因为第二个按钮是SivaLoginScreen的子控件,kv里的root关键字就代表当前的SivaLoginScreen实例,把第二个按钮的on_release改成这样就行:

ImageButton:
    id: second_button
    source: {'normal': 'images/second.png', 'down': 'images/second-down.png'} [self.state]
    on_release: root.func_authentication()

方式2:通过屏幕管理器定位目标屏幕(可选)

如果之后需要从其他组件调用这个方法,可以通过屏幕管理器的get_screen方法拿到SivaLoginScreen实例,比如在Python代码里可以这么写:

# 示例:在App类或其他地方调用
self.root.get_screen('login_screen').func_authentication()

额外优化建议

你还可以把func_authentication的实现改得更健壮一点,每个Screen实例都自带manager属性,指向它所属的ScreenManager,用这个替代app.root会更灵活:

class SivaLoginScreen(Screen):
    def func_authentication(self):
        self.manager.current = 'tabbed_screen'

修改后的完整关键代码片段

kv文件(仅修改第二个按钮的事件)

<SivaLoginScreen>:
    name: 'login_screen'
    # ...其他原有代码不变...
    BoxLayout:
        id:login_button_layout
        orientation: 'horizontal'
        size_hint: 0.2, 0.2
        pos_hint: {'center_x':0.5, 'center_y':0.25}
        ImageButton:
            id: first_button
            source: {'normal': 'images/first.png', 'down': 'images/first-down.png'} [self.state]
            on_release: app.root.current='tabbed_screen'
        ImageButton:
            id: second_button
            source: {'normal': 'images/second.png', 'down': 'images/second-down.png'} [self.state]
            on_release: root.func_authentication()

这样改完之后,第二个按钮就能正常触发屏幕切换了~

内容的提问来源于stack exchange,提问作者Shoumik Das

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 14:27:51