在python中从列表中检索整数

2024-04-24 01:01:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在试图检索保存到列表中的随机整数列表“自动按钮". 但是我无法成功访问它们

    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>]

相反,我希望整数打印在列表中! 任何帮助都将不胜感激,蒂亚


Tags: inself列表forobjectmainrange整数
2条回答

输出正确。基本上,您对print语句所做的是打印列表中的项目”自动按钮“恰好是类按钮的对象。你知道吗

如果指定您使用的是PyQT4框架,请更正我的错误,但PyQT4不包含名为“Button”的类。假设你用了“导入。。。作为“option”,而不是“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()函数的返回值。你知道吗

你可以试试:

print (button.numberLabel for button in self.buttons)

我希望这对你有帮助。你知道吗

相关问题 更多 >