【问题标题】:Can't update image source in Kivy project无法在 Kivy 项目中更新图像源
【发布时间】:2021-03-07 00:51:45
【问题描述】:

我想更改播放/暂停按钮的图像(一次是“play_icon.png”用于播放,一次是“pause_icon.png”)。问题是我是编程新手,我不知道为什么图像没有更新。我有一个名为 Icon(Image) 的类和其中的源图像,我正在更改 KivyApp(App) 类的源图像。当我从 KivyApp 打印源代码时,我看到它发生了变化,但按钮上的图像没有变化。

这是我项目中的一些代码:

main.py

class Icon(Image):
def __init__(self, **kwargs):
    super(Icon, self).__init__(**kwargs)
    self.source = 'play_icon.png'

class KivyApp(App):

    app = App.get_running_app()

    def build(self):
        return ScreenManagement()

    def start_stop(self):
        if <condition>:
            Icon.source = 'pause_icon.png'
        else:
            Icon.source = 'play_icon.png'

kivy.kv

Button:
    id: btn
    on_press: app.start_stop()
    Icon:
        id: icon
        source: self.source
        size: self.parent.size
        x: self.parent.x
        y: self.parent.y
        keep_ratio: True

【问题讨论】:

    标签: python kivy


    【解决方案1】:

    Icon.source = 'pause_icon.png'

    这将更改Icon 类的source 属性,这对您创建的该类的实例没有任何影响。

    您需要更改您在 gui 中显示的 Icon 类实例的 source 属性。

    【讨论】:

    • 感谢您的快速回复。现在我正在尝试像这样更改source 属性:self.root.ids.mainpage.ids.btn.ids.icon.source = 'pause_icon.png',我收到此错误:'super' object has no attribute '__getattr__'
    • 您可能正试图在 ID 存在之前对其进行访问。尝试反转它:使用source: app.source,然后在应用程序类中使用source = StringProperty()。然后,您可以更改 App.get_running_app().source 以将更改传播到您的小部件实例。
    猜你喜欢
    • 1970-01-01
    • 2016-08-17
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    相关资源
    最近更新 更多