我用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
问题
根本原因
属性/变量
image
在RootLayout
/AnchorLayout
对象中不存在解决方案
image
是分配给kv文件中的id
小部件的Image
。因此,要访问Python代码中的Image
对象,需要添加ids
self.ids.image.source
替换self.image.source
self.image.fonte = "tachanka2.jpg"
,因为Image
小部件中没有属性fonte
相关问题 更多 >
编程相关推荐