Reputation: 321
I'm having trouble dynamically adding widgets in my kv file, everything I've seen so far has been around adding widgets in the py file. The reason I'd like to use the kv file for this is that I've got a modified Button widget I'd like to use that's written in the kv file and I don't know how to create it in the py file.
So I guess there are two possible questions:
1) How do I use add_widget correctly in the kv file. In the below code I get the NameError: SmoothButton is not defined.
Or
2) How do I create my SmoothButton in the py file?
kv file:
WindowManager:
ChatPage:
<ChatPage>:
name: "chat_page"
NavigationLayout:
id: nav_layout
MDNavigationDrawer:
NavigationDrawerIconButton:
text: "Test"
on_release: app.root.current = "login"
FloatLayout:
MDToolbar:
pos_hint: {'top': 1}
md_bg_color: 0.2, 0.6, 1, 1
left_action_items: [['menu', lambda x: root.ids.nav_layout.toggle_nav_drawer()]]
Button:
text: "Create button"
pos_hint: {"x": 0.65, "top": 0.15}
size_hint: 0.35, 0.15
on_release: root.add_widget(SmoothButton)
<SmoothButton@Button>:
background_color: 0,0,0,0
background_normal: ""
back_color: 1,0,1,1
border_radius: [6]
canvas.before:
Color:
rgba: self.back_color
RoundedRectangle:
size: self.size
pos: self.pos
radius: self.border_radius
py file:
import kivy
from kivy.app import App
from kivy.properties import ObjectProperty, StringProperty, NumericProperty, ListProperty
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
from kivy.uix.popup import Popup
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.core.window import Window
from kivymd.theming import ThemeManager
import mysql.connector
from kivymd.uix.picker import MDDatePicker
class ChatPage(Screen):
pass
class WindowManager(ScreenManager):
pass
class MyApp(App):
theme_cls = ThemeManager()
def build(self):
kv = Builder.load_file("kivy.kv")
sm = WindowManager()
screens = [ChatPage(name="chat_page")]
for screen in screens:
sm.add_widget(screen)
sm.current = "chat_page"
return sm
if __name__ == '__main__':
MyApp().run()
Thanks
Upvotes: 2
Views: 2624
Reputation: 243887
If you want to add modified widgets in the .kv it doesn't mean you have to add it there. The solution is to expose the modified widget in the .kv to the .py, and create a method in "ChatPage" where you add the widget:
*.py
# ...
class SmoothButton(Button):
pass
class ChatPage(Screen):
def on_released(self):
self.add_widget(SmoothButton())
# ...
*.kv
# ...
<ChatPage>:
name: "chat_page"
NavigationLayout:
id: nav_layout
MDNavigationDrawer:
NavigationDrawerIconButton:
text: "Test"
on_release: app.root.current = "login"
FloatLayout:
MDToolbar:
pos_hint: {'top': 1}
md_bg_color: 0.2, 0.6, 1, 1
left_action_items: [['menu', lambda x: root.ids.nav_layout.toggle_nav_drawer()]]
Button:
text: "Create button"
pos_hint: {"x": 0.65, "top": 0.15}
size_hint: 0.35, 0.15
on_release: root.on_released() # <---
<SmoothButton>: # <---
background_color: 0,0,0,0
# ...
Upvotes: 2