我想将图像源值传递给kivy中的kv文件。这就是我所做的。
#main.py
from kivy.uix.boxlayout import BoxLayout
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import StringProperty
from kivy.uix.image import Image
class Page(BoxLayout):
id1=StringProperty()
def __init__(self):
super(Page, self).__init__()
self.id1="ellow"
self.img=StringProperty("logo.jpg")
class SimpleKivyApp(App):
def build(self):
return Page()
a=SimpleKivyApp()
a.run()
KV文件
#simplekivy.kv
<Page>:
canvas.before:
Color:
rgba:0,0,1,1
Rectangle:
pos: self.pos
size: self.size
Image:
pos_hint:{"center_x":0.4,"y":0.3}
color:255,1,1,1
size:70,70
source: root.img
Label:
pos:0,0
font_size:80
text:root.id1
Button:
size_hint:0.5,0.2
font_size:60
text:"Start"
on_press: app.onClick()
当我运行它给我这个错误
AttributeError:“页面”对象没有属性“ img”
最佳答案
首先在窗口小部件的__init__
方法中评估kv文件。在设置super
之前,这会在self.img
调用中发生。您必须在super
之前声明属性,或将属性声明为类属性而不是实例属性。您可以在py
(与id1
相同)或kv
中进行:
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.app import App
from kivy.properties import StringProperty
kv_text = '''
#simplekivy.kv
<Page>:
img: '' #<<<<<<<<<<<<<<<<<<
canvas.before:
Color:
rgba:0,0,1,1
Rectangle:
pos: self.pos
size: self.size
Image:
pos_hint:{"center_x":0.4,"y":0.3}
color:255,1,1,1
size:70,70
source: root.img
Label:
pos:0,0
font_size:80
text:root.id1
Button:
size_hint:0.5,0.2
font_size:60
text:"Start"
on_press: app.onClick()
'''
class Page(BoxLayout):
id1=StringProperty()
def __init__(self):
super(Page, self).__init__()
self.id1="ellow"
self.img="logo.jpg"
class SimpleKivyApp(App):
def build(self):
Builder.load_string(kv_text)
return Page()
if __name__ == '__main__':
SimpleKivyApp().run()
关于python - 如何在kivy中将图像值从python传递到kv文件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45114311/