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

如何在KivyCamera类中打印KivyCameraApp类里self.result2的值?

在KivyCamera类中访问KivyCameraApp的result2值的方法

以下是两种可行的实现方式:

方法一:通过App.get_running_app()获取当前应用实例

Kivy提供了App.get_running_app()方法,可直接获取当前运行的应用实例,进而访问其属性。示例代码如下:

from kivy.app import App
from kivy.uix.image import Image
from kivy.uix.screenmanager import ScreenManager

class KivyCamera(Image):
    def __init__(self, capture, fps, **kwargs):
        super(KivyCamera, self).__init__(**kwargs)
        # 获取当前应用实例
        current_app = App.get_running_app()
        # 打印result2(需确保switch_to_camera已执行,否则result2可能未定义)
        print(current_app.result2)

class KivyCameraApp(App):
    def build(self):
        self.sm = ScreenManager()
        # 此处补充camera_screen的创建与添加逻辑
        return self.sm

    def switch_to_camera(self):
        self.sm.current = 'camera_screen'
        self.result2 = self.sm.current

方法二:初始化时传入App实例

创建KivyCamera对象时,直接将KivyCameraApp的实例作为参数传入并保存,后续即可直接访问其属性:

from kivy.uix.image import Image
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager

class KivyCamera(Image):
    def __init__(self, capture, fps, app_instance, **kwargs):
        super(KivyCamera, self).__init__(**kwargs)
        self.app = app_instance
        # 打印result2(需确保switch_to_camera已执行)
        print(self.app.result2)

class KivyCameraApp(App):
    def build(self):
        self.sm = ScreenManager()
        # 创建KivyCamera时传入当前App实例
        camera_widget = KivyCamera(capture=None, fps=30, app_instance=self)
        # 此处补充camera_widget添加到camera_screen的逻辑
        return self.sm

    def switch_to_camera(self):
        self.sm.current = 'camera_screen'
        self.result2 = self.sm.current

注意事项

  • 访问result2前必须确保switch_to_camera方法已被调用,否则会出现属性未定义的错误。若需在KivyCamera初始化时就访问,可在App类的初始化逻辑中给result2设置初始值(比如self.result2 = "")。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 02:40:54