Reputation: 13
OK so what I want to do is have a FloorWidget with a option to add rooms dynamically with a press of a button while the app is running. I want to load specific graphic based on the room number and I don't know how to achive that in .kv file
<RoomWidget>:
id: room_widget
room_num: # would be great if you could pass this as an argument
Image:
source: os.path.join(GRAPHICS_DIR_PATH, "room" + str(room_widget.room_num))
Is there a way to do this? Could I somehow initilize room_num in python file by passing it into the RoomWidget constructor and access it in .kv file?
class RoomWidget(Screen, Widget):
def __init__(self, room_num, **kwargs):
super().__init__(**kwargs)
self.room_num = room_num
<RoomWidget>:
size_hint: (.2, .35)
source: os.path.join(GRAPHICS_DIR_PATH, "room" + str(self.room_num))
Image:
source: source
If I do sth like this I get an error: AttributeError: 'RoomWidget' object has no attribute 'room_num'.
Upvotes: 1
Views: 802
Reputation: 38962
You can do that by making a property
of RoomWidget
Like this:
class RoomWidget(Screen):
room_num = NumericProperty()
def __init__(self, room_num, **kwargs):
super().__init__(**kwargs)
self.room_num = room_num
Then, in your 'kv':
#:import os os
#:set GRAPHICS_DIR_PATH '.'
<RoomWidget>:
size_hint: (.2, .35)
source: os.path.join(GRAPHICS_DIR_PATH, "room" + str(self.room_num) + '.png')
Image:
source: root.source
Note that you do not need to extend both Screen
and Widget
, because Screen
is a Widget
.
Upvotes: 1