开发者

Python: Dynamic attribute name generation without exec() or eval()

开发者 https://www.devze.com 2022-12-24 20:13 出处:网络
I\'m trying to dynamically create buttons at runtime with PyQT4.7 However, this being my first python program I\'m not sure how to get the functionality I want.

I'm trying to dynamically create buttons at runtime with PyQT4.7

However, this being my first python program I'm not sure how to get the functionality I want.

I would like to be able to substitute a text string for an attribute name:

i.e.

for each in xrange(4):
    myname = "tab1_bu开发者_开发问答tton%s" % each  #tab1_button0, tab1_button1, tab1_button2

    #self.ui.tab1_button0 = QtGui.QPushButton(self.ui.tab) <--normal code to create a named button
     setattr(self.ui,myname,QtGui.QPushButton(self.ui.tab)) #rewrite of line above to dynamicly generate a button

#here's where I get stuck. this code isn't valid, but it shows what i want to do
     self.ui.gridLayout.addWidget(self.ui.%s) % myname
#I need to have %s be tab1_button1, tab1_button2, etc. I know the % is for string substituion but how can I substitute the dynamically generated attribute name into that statement?

I assume there's a basica language construct I'm missing that allows this. Since it's my first program, please take it easy on me ;)


If I interpreted this correctly, I think what you want is this:

self.ui.gridLayout.addWidget(getattr(self.ui,myname))

Give that a go. In Python the following two statements are functionally equivalent (from the link below):

value = obj.attribute
value = getattr(obj, "attribute-name")

For extra context:

http://effbot.org/zone/python-getattr.htm


Just assign the button to a variable so you can both set the attribute and add the widget.

for i in range(4):
    name = 'button%d' % i
    button = QtGui.QPushButton(...)
    setattr(self, name, button)
    self.ui.gridLayout.addWidget(button)

Personally I would add the buttons to a list instead of giving them different names.


I think you might benefit from knowledge of lists (commonly called arrays in other languages)

self.buttons = [None, None, None, None]
for each in xrange(4):
     self.buttons[each] = QtGui.QPushButton(self.ui.tab)
     self.ui.gridLayout.addWidget(self.buttons[each])

For a tutorial on Python lists: http://effbot.org/zone/python-list.htm

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号