ok, look can anyone give an example in kivy .kv file of a button that is set to a command that when you press it,it will make a label beneath the button, I attempted this
python
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.uix.label import Label
Builder.load_file("my.kv")
class MyLayout(Widget,App):
def __init__(self, **kwargs):
super(MyLayout, self).__init__(**kwargs)
def addthelabel(self):
self.button = Label(text"you have just added me")
self.add_widget(self.button)
class UiApp(App):
def build(self):
return MyLayout()
UiApp().run()
.kv file
<MyLayout>:
BoxLayout:
orientation:"horizontal"
size: root.width, root.height
Button:
text:"hello"
on_press:
root.addthelabel()
but when I ran it and clicked the button it's not what I expected IMAGE https://i.sstatic.net/ZoOCj.png so I need a fresh example can you guys help.
The reason you are seeing this behaviour is because in addthelabel()
, the new Label
is being added as a child of the root MyWidget
layout, rather than to the BoxLayout
that contains the existing button.
To get the behaviour you want you need to add an id
to the BoxLayout
in the kv
file that allows you to access that widget from the Python code. You also need to change the orientation
to vertical
.
<MyLayout>:
BoxLayout:
id: layout
orientation:"vertical"
size: root.width, root.height
Button:
text:"hello"
on_press: root.addthelabel()
Then in the Python code, instead of adding the new Label
to the root widget, we want to add it to the BoxLayout
using its new id
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.uix.label import Label
Builder.load_file("my.kv")
class MyLayout(Widget,App):
def __init__(self, **kwargs):
super(MyLayout, self).__init__(**kwargs)
def addthelabel(self):
self.button = Label(text="you have just added me")
self.ids.layout.add_widget(self.button)
class UiApp(App):
def build(self):
return MyLayout()
UiApp().run()