![](/img/trans.png)
[英]Retrieving values from backwards relationship as a list of integers instead of list of tuples?
[英]Retrieving integers from list in python
我正在嘗試檢索保存到列表“ self.buttons”中的隨機整數列表。 但是我無法成功訪問它們
moveButton = 70
self.buttons = []
for i in range(5):
numberLabel = random.randint(-1000,1000)
self.buttons.append(Button(str(numberLabel), self))
self.buttons[i].setFixedSize(160, 80)
self.buttons[i].move(moveButton,200)
moveButton = moveButton + 160
self.buttons[i].show()
print(self.buttons)
當我嘗試打印列表時,我得到...
[<__main__.Frame object at 0x10b1d25f0>, <__main__.Frame object at 0x10b1d2680>, <__main__.Frame object at 0x10b1d2710>, <__main__.Frame object at 0x10b1d27a0>, <__main__.Frame object at 0x10b1d2830>]
相反,我希望整數顯示在列表中! 任何幫助將不勝感激,TIA
您可以嘗試:
print (button.numberLabel for button in self.buttons)
希望對您有所幫助。
輸出正確。 基本上,您使用print語句所做的是正在打印列表“ self.buttons”的項目,而這些列表恰好是Button類的對象。
您指定您使用的是PyQT4框架,如果我錯了,請糾正我,但PyQT4不包含名為“ Button”的類。 假設您使用“ import ... as”選項,而不是“ Button”,則表示“ QPushButton”,則需要將代碼的最后一行從以下位置更改:
for i in range(5):
numberLabel = random.randint(-1000,1000)
self.buttons.append(Button(str(numberLabel), self))
self.buttons[i].setFixedSize(160, 80)
self.buttons[i].move(moveButton,200)
moveButton = moveButton + 160
self.buttons[i].show()
print(self.buttons)
至:
for i in range(5):
numberLabel = random.randint(-1000,1000)
self.buttons.append(Button(str(numberLabel), self))
self.buttons[i].setFixedSize(160, 80)
self.buttons[i].move(moveButton,200)
moveButton = moveButton + 160
self.buttons[i].show()
print(self.buttons[i].text())
這樣,您不會在內存中打印對象的位置,而是在打印text()函數的返回值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.