【问题标题】:Why can't I add an image using kivy in the main.py?为什么我不能在 main.py 中使用 kivy 添加图像?
【发布时间】:2021-11-10 12:33:01
【问题描述】:

代码:

from kivy.uix.widget import Widget
from kivy.uix.image import Image

class MainWidget(Widget):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.add_cloud()

    def add_cloud(self):
        img = Image(source="images/cloudbig.png")
        return img

class TestApp(App):
    pass

TestApp().run()

应该使用 Kivy 库打开应用程序,添加一个小部件,然后添加一个图像。虽然图像没有显示在窗口中,但我只是得到一个空窗口。

我尝试使用单独的 .kv 文件添加图像,该文件有效,但我需要在 .py 文件的函数中添加图像以循环该函数。

如何修复屏幕上不显示的图像?

【问题讨论】:

    标签: python image kivy


    【解决方案1】:

    你这个问题的原因是:

    • 您不能仅通过从方法/函数返回对象来添加小部件(具体而言是 Image 小部件),而是使用 self.add_widget 方法
    • 您没有在 TestApp 类中创建任何 build 方法,如果您不使用 kivy 设计语言,这基本上是必需的

    这是您的代码示例,已修复:

    from kivy.app import App
    from kivy.uix.widget import Widget
    from kivy.uix.image import Image
    
    
    class MainWidget(Widget):
        def __init__(self, **kwargs):
            super().__init__(**kwargs)
    
            self.add_cloud()
    
        def add_cloud(self):
            img = Image(source="images/cloudbig.png")
            self.add_widget(img)
    
    class TestApp(App):
        def build(self):
            xd = MainWidget()
            return xd
    
    TestApp().run()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-11
      • 2023-03-05
      • 2016-05-04
      • 1970-01-01
      相关资源
      最近更新 更多