我如何在Python中增加最后一个字符串字符,而不是写10次相同的东西?
.
.
groupBox.setFont(QtGui.QFont('SansSerif', 15))
.
.
state1= QtGui.QPushButton("xyz")
state2= QtGui.QPushButton("124")
.
.
state10= QtGui.QPushButton("abc") # these stuff are to be assigned with different titles
state1.setFont(QtGui.QFont('Times', 10)
state2.setFont(QtGui.QFont('Times', 10)
.我只想在这里增加,将相同的字体应用于所有项目,如下所示(我需要为我的GroupBox和QPushButton设置不同的字体)
for i in xrange(10):
"state" + str(i).setFont(QtGui.QFont('Times', 10))发布于 2015-09-23 15:25:53
只需创建一个列表,然后append并修改数据。
ButtonNames=['hello','world'] #fill this manually
Buttons=[]
for name in ButtonNames:
Buttons.append(QtGui.QPushButton(name))
for btn in Buttons:
btn.setFont(QtGui.QFont('Times', 10)
vbox.addWidget(btn)
for k in xrange(0,len(ButtonNames)):
Buttons[k].setTooltip("Click here for {}".format(ButtonNames[k])在示例中,您要做的是从string对象调用一个方法。当然,它不存在,这就是它不能工作的原因。
发布于 2015-09-23 15:37:21
其他人已经提出了列表(我认为这是一个很好的方法),但如果您仍然需要/希望能够按名称引用元素,您还可以使用字典:
states = {'first':QtGui.QPushButton("xyz"),\
'second':QtGui.QPushButton("124"),\
'tenth':QtGui.QPushButton("bla")}
# looping over all:
for state in states.values():
state.setFont(QtGui.QFont('Times', 10)
# addressing a single one:
states['second'].setFont(QtGui.QFont('Times', 12)这样,您可以轻松地遍历所有这些文件,但是仍然可以给出更容易记住的名称。
发布于 2015-09-23 15:27:48
你不能在蟒蛇身上做这种事
但是,如果state1..state10是对象的成员,则可以:
class MyObj:
def __init__(self):
for i in xrange(1,10):
self.__dict__['state%d' % i] = QtGui.QPushButton("124")但你为什么要这么做?只是太丑了。用一个列表代替。
https://stackoverflow.com/questions/32743517
复制相似问题