I am trying to do the same as I did to add these widgets, but without success. I am working with the kv language and bind function. With this code below is possible add a buttons dynamically, but isn't possible remove them.
.py
class PrimeiroScreen(Screen):
def __init__(self, **kwargs):
self.name = 'um'
super(Screen,self).__init__(**kwargs)
def fc2(self):
btn = Button(text="Botão",size_hint=(.1,.1))
self.ids.grade2.add_widget(btn)
btn.bind(on_press=self.printa)
def printa(self,*args):
#btn2 = Button(text="Btn2",size_hint=(.1,.1))#I can add another btn succesfully
self.ids.grade2.add_widget(btn2)#but I can do the same by this way
self.remove_widget(btn)
grade2.remove_widget(self.btn)
and the .kv
<RootScreen>:
PrimeiroScreen:
<PrimeiroScreen>:
GridLayout:
cols: 1
size_hint: (.5,1)
id: grade
Button:
text: "hi!"
on_press: root.fc2()
StackLayout:
orientation: 'bt-rl'
GridLayout:
cols: 2
size_hint: (.5,1)
id: grade2
Has anybody any idea of the mistake I made? Python shows me the message below:
self.remove_widget(btn)
NameError: global name 'btn' is not defined
The Widget class is the base class required for creating Widgets. This widget class was designed with a couple of principles in mind: Event Driven. Widget interaction is built on top of events that occur. If a property changes, the widget can respond to the change in the 'on_<propname>' callback.
pos : pos stands for position i.e it is used to position the widget. By default (0, 0), the bottom-left corner of the screen is the default position of the button in kivy python.
FloatLayout honors the pos_hint and the size_hint properties of its children. For example, a FloatLayout with a size of (300, 300) is created: layout = FloatLayout(size=(300, 300))
The GridLayout arranges children in a matrix. It takes the available space and divides it into columns and rows, then adds widgets to the resulting “cells”. Changed in version 1.0. 7: The implementation has changed to use the widget size_hint for calculating column/row sizes.
Changebtn = Button(text="Botão",size_hint=(.1,.1))
toself.btn = Button(text="Botão",size_hint=(.1,.1))
So you make it a class attribute.
And then remove it like thisself.remove_widget(self.btn)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With