【问题标题】:Why can't I acces my image's source using Screenmanager and ObjectProperty?为什么我不能使用 Screenmanager 和 ObjectProperty 访问我的图像源?
【发布时间】:2020-10-07 21:19:07
【问题描述】:

我想通过指向图片的 ID 来访问图片的来源。 当我在不使用 ScreenManager 的情况下尝试这种方式时,它工作正常,但使用 ScreenManager 并给出以下错误消息:

AttributeError: 'kivy.properties.ObjectProperty' 对象没有属性 'source'

那么您知道如何使用 ScreenManager 访问我的图像吗?

Python 代码:

from kivy.app import App
from kivy.properties import ObjectProperty

from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.image import Image


class MainWindow(Screen):

    img1 = ObjectProperty(None)

def __init__(self, **kwargs):
    super(MainWindow, self).__init__(**kwargs)

    self.print_image()

def print_image(self):
    print(self.img1)


class SecondWindow(Screen):
    pass


class WindowManager(ScreenManager):
    pass


Gui = Builder.load_file("my.kv")


class MyApp(App):
    def build(self):
        return Gui


if __name__ == "__main__":
    MyApp().run()

kv代码:

WindowManager:
    MainWindow:
    SecondWindow:

<MainWindow>:
    name: "main"
    img1: img1

    Button:
        id: b1
        text: "Submit"

    Image:
        id: img1
        source: "IMG_8681.jpg"


<SecondWindow>:
    name: "second"

    Button:
        text: "Go Back"
        on_release:
            app.root.current = "main"
            root.manager.transition.direction = "right"

提前非常感谢!

【问题讨论】:

    标签: python properties kivy kivy-language


    【解决方案1】:

    您可以按照您的描述访问Image,但是在加载类时,甚至在加载kv 文件之前,在任何方法之外的类中执行print 语句。

    您可以像这样访问Image

    print(Gui.get_screen('main').img1)
    

    或者在MainWindow类的方法中,你可以使用:

    print(self.img1)
    

    但你必须等到App 启动

    【讨论】:

    • 正如我在回答中所说:“您必须等到应用程序启动”。 MainWindow__init__()方法在App启动之前执行。
    猜你喜欢
    • 2023-01-09
    • 2011-04-25
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 2014-07-05
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    相关资源
    最近更新 更多