Reputation: 1412
I am facing a very basic issue here . I want to create 100s of Buttons and to make them I want to use loops preferably for loop and create Button Names in the loop itself so i can use it later in the program logic i.e. example for i=1 i want to create Button1 and for i=100 i want button Button100 , however i am not sure how to do that in Python Kivy .
This is same thing which we can do in Linux using &variable name and sometime eval .Please see the code below for better . Comments will describe the issue here :
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.graphics import Color
from kivy.clock import Clock
class RootWidget(GridLayout):
pass
class MainApp(App):
def build(self):
self.parent = GridLayout(cols=6)
for i in (1,2,3,4,5,6):
for j in (1,2,3,4,5,6):
#Want to make self.BName s value as ButtonName%s%s
self.BName= 'ButtonName%s%s'%(i,j)
print "Button Name should be ",self.BName
self.BName = Button(text='%s%s'%(i,j))
self.parent.add_widget(self.BName)
Clock.schedule_once(lambda a:self.update(),1)
return self.parent
def update(self):
print "I am update function"
for child in self.parent.children:
print child
#Want to make use ButtonName11 and not BName
self.BName.text = "hello"
#self.ButtonName11.text= "hello"
if __name__ == '__main__':
MainApp().run()
Upvotes: 0
Views: 295
Reputation: 1347
Scorpion_God way of doing it should work, however, a clearer way is using setattr.
Here's some example code:
class Foo(object):
def create_buttons(self):
for i in range(10):
setattr(self, 'my_name{}'.format(i), i)
foo = Foo()
foo.my_name3
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'my_name3'
foo.create_buttons()
foo.my_name3
3
Upvotes: 0
Reputation: 1509
Have you tried using this concept?
class Foo:
def __init__(self):
for i in range(100):
self.__dict__['Button{}'.format(i)] = Button(text='Button no. {}'.format(i))
>>> foo = Foo()
>>> foo.Button5.text
Button no. 5
>>> foo.Button98.text
Button no. 98
Upvotes: 1