Reputation: 3
Is there a way to access a widget from another Dynamic Class in Kivy? I'm trying to trigger some event from a dynamic class which is going to have an effect on a other dynamic class.
Here's an example:
Python:
from kivy.app import App
from kivy.lang.builder import Builder
Builder.load_file("ui version control/dropdowns_and_buttons.kv")
class MyApp(App):
def build(self):
return Builder.load_file("main_ui.kv")
MyApp().run()
The main_ui.kv file:
MDGridLayout:
dropdown_default: "-- Select --"
cols: 2
size_hint: 1, 0.3
pos_hint: {"center": (0.5, 0.65)}
spacing: 30
DropdownMenu:
id: name_menu
text: root.dropdown_default
color: (0.5, 0.5, 0.5, 0.7) if self.text == root.dropdown_default else app.theme_cls.text_color
values: ['name1', 'name2', 'name3']
on_text: self.text
DropdownMenu:
id: number_menu
text: root.dropdown_default
color: (0.5, 0.5, 0.5, 0.7) if self.text == root.dropdown_default else app.theme_cls.text_color
values: [f"{i}" for i in range(1, 46)]
on_text: self.text
And an additional dropdowns_and_buttons.kv file having custom dropdown widget and button in a separate kv file
<DropdownMenu@Spinner>:
dropdown_cls: Factory.CustomDropdown
option_cls: Factory.DropdownOptions
background_normal: ""
background_color: 0, 0, 0, 0
canvas.before:
Color:
rgba: 0, 0, 0, 0.4
RoundedRectangle:
size: self.size
pos: self.pos
radius: [6]
Color:
rgba: 0.5, 0.4, 0.5, 0.5
Line:
width: 1
rounded_rectangle: self.x, self.y, self.width, self.height, 6, 6, 6, 6, 100
MDLabel:
id: dd_label
text: "Changing text"
center_x: root.center_x + 110
center_y: root.center_y
<DropdownOptions@SpinnerOption>:
background_normal: ""
background_color: 0, 0, 0, 0
canvas:
Color:
rgba: 0.4, 0.4, 0.4, 0.6
Line:
width: 1
points: self.x+10, self.y, self.width-10, self.y
<CustomDropdown@DropDown>:
canvas.before:
Color:
rgba: 0, 0, 0, 0.4
RoundedRectangle:
size: self.size
pos: self.pos
radius: [0, 0, 6, 6]
on_dismiss: print(root.DropdownMenu.ids.dd_label.text)
I'm trying to use dd_label
widget from DropdownMenu
class in CustomDropdown
class. So far, I can access it using app.root.ids.name_menu.ids.dd_label
on on_dismiss
but, I feel like it's not an ideal way to go about it.
Now, I know on_dismiss
will throw an error because it's not accessing the intended widget MDLabel
from DropdownMenu
class.
Can someone help me figure out how I can access dd_label
widget from CustomDropdown
class?
Upvotes: 0
Views: 217
Reputation: 3
Found a way. To use widgets from other dynamic class, I needed to use Factory
to create an instance of DropdownMenu
in CustomDropdown
class.
Like this: on_dismiss: print(Factory.DropdownMenu().ids.dd_label.text)
Upvotes: 0
Reputation: 5949
I would use the attach_to
property of the DropDown
class, which will reference the Spinner
/DropDownMenu
instance.
on_select: print(self.attach_to.ids.dd_label.text)
.
Upvotes: 1