Skip to main content
 首页 » 编程设计

python之为什么不能在元组对象上调用函数

2025年05月04日30telwanggs

bStart 和 bStop click 函数确实执行相同的操作,但 bStop 函数调用错误。

为什么不能在元组对象上调用 .hide()?

from PyQt5.QtWidgets import (QApplication, QFrame, QGridLayout, QHBoxLayout, QPushButton, QSizePolicy, QSpacerItem, QToolButton, QVBoxLayout, QWidget, QLabel) 
 
import frames 
 
class GUI(QWidget): 
    def __init__(self, parent=None): 
        super(GUI, self).__init__(parent=parent) 
        self.principalLayout = QHBoxLayout(self) 
        self.controlFrame = QFrame(self)  
        self.gridLayout = QGridLayout(self.controlFrame) 
        self.principalLayout.addWidget(self.controlFrame) 
 
        self.widgets() 
 
        print (self.bStart) 
        print(buttons(self)) 
    def widgets(self): 
        self.bStart = QPushButton('Start') 
        self.gridLayout.addWidget(self.bStart, 0, 0) 
        self.bStart.clicked.connect(lambda: self.hide_layout(self.bStart, self.bStop)) 
 
        self.bStop = QPushButton('Stop') 
        self.bStop.clicked.connect(lambda: self.hide_layout(buttons(self))) 
        self.gridLayout.addWidget(self.bStop, 0, 2) 
 
    def hide_layout(self, *args): 
        for a in args: 
            a.hide() 
 
 
    def show_layout(self, *args): 
        for a in args: 
            a.show() 
 
def buttons(self): 
    return (self.bStart, self.bStop) 
 
if __name__ == '__main__': 
    import sys 
    app = QApplication(sys.argv)     
    w = GUI() 
    w.show() 
    sys.exit(app.exec_()) 

打印输出b开始按钮:

<PyQt5.QtWidgets.QPushButton object at 0x7f089fddac18> 

打印输出buttons()函数:

(<PyQt5.QtWidgets.QPushButton object at 0x7f089fddac18>, <PyQt5.QtWidgets.QPushButton object at 0x7f089fddadc8>) 

错误b停止按钮点击:

Traceback (most recent call last): 
  File "gui.py", line 23, in <lambda> 
    self.bStop.clicked.connect(lambda: self.hide_layout(buttons(self))) 
  File "gui.py", line 28, in hide_layout 
    a.hide() 
AttributeError: 'tuple' object has no attribute 'hide' 

请您参考如下方法:

您忘记解压元组:

self.bStop.clicked.connect(lambda: self.hide_layout(*buttons(self)))