“RootLayout”对象没有属性“image”

2024-10-02 10:27:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Kivy编写了一个程序,当按下按钮时,会得到一个随机的图像。 我写了代码,但是当我想更改源代码时,我得到了以下错误:AttributeError: 'RootLayout' object has no attribute 'image'

Python:

class MinimalApp(App):
    images_defenders2 = list(images_defenders)
    title = 'My App'
    def build(self):
        number = random.randrange(0, length_code_list1)
        img = (images_attackers[number]) #The variable with the random photo
        print(img)
        root = RootLayout()
        return(root)
class RootLayout(AnchorLayout):
   def say_hello(self):
       def callback(self):
           fonte = StringProperty('tachanka2.jpg')
           self.image.source = (fonte)
           self.image.fonte = "tachanka2.jpg"
       callback(self)  
   pass

if __name__ == '__main__':
    MinimalApp().run()

千伏:

#:kivy 1.7.2
#:import kivy kivy
#:import random random

<RootLayout>:
    anchor_x: 'center'                              
    anchor_y: 'center'
    Image:
        id: image
        source: 'nokk.png'
        size: self.texture_size
   AnchorLayout:
        anchor_x: 'left'
        anchor_y: 'bottom'

    Button:
        text: 'Attacco'
        size_hint: 0.5, 0.2
        font_size:64
        on_press: {root.say_hello()}
   AnchorLayout:
    anchor_x: 'right'
    anchor_y: 'bottom'

    Button:
        text: 'Difesa'
        size_hint: 0.5, 0.2
        font_size:64

我试图在kv文件中直接更改源代码,我成功了,但是我需要在python文件中更改它,因为我必须创建一个函数,从列表中随机显示一张照片并将其放入变量中。 然后将此变量作为图像的源。 所以请帮助我理解为什么会出现错误,以及如何修复它。 导致此错误的代码如下:

class RootLayout(AnchorLayout):
    def say_hello(self):
        def callback(self):
            fonte = StringProperty('tachanka2.jpg')
            self.image.source = (fonte)
            self.image.fonte = "tachanka2.jpg"
        callback(self)  
    pass

Tags: imageselfsizedef错误callbackrandomclass
1条回答
网友
1楼 · 发布于 2024-10-02 10:27:15

问题

AttributeError: 'RootLayout' object has no attribute 'image'

根本原因

属性/变量imageRootLayout/AnchorLayout对象中不存在

解决方案

image是分配给kv文件中的id小部件的Image。因此,要访问Python代码中的Image对象,需要添加ids

  • self.ids.image.source替换self.image.source
  • 删除self.image.fonte = "tachanka2.jpg",因为Image小部件中没有属性fonte

相关问题 更多 >

    热门问题