
[英]How to fix Attributive Error bool object has no attribute choices in python
[英]Error "bool object has no attribute" python message
我有一个 getFile function ,它将获取 csv 文件的地址并在命令控制台中打印文件名。 当我在主 window 中运行 function 时,我不断收到“'bool' object has no attribute 'filename'”。 为什么会这样?
ttreadfile.py
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
def getFile(self):
"""this function will get the address of the sdv file location"""
self.filename = QFileDialog.getOpenFileName(filter = "csv (*.csv)")[0]
print("File:",self.filename)
工具包
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from Module.ttreadfile import *
class ApplicationWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
"""set layout of window"""
self.main_widget = QWidget(self)
l = QGridLayout(self.main_widget)
open_button =QPushButton('Open')
open_button.clicked.connect(getFile)
l.addWidget(open_button, 0,0)
if __name__ == '__main__':
app = QApplication(sys.argv)
aw = ApplicationWindow()
aw.setWindowTitle("PyQt5 Matplot Example")
aw.show()
#sys.exit(qApp.exec_())
app.exec_()
QPushButton
小部件从 QAbstractButton 继承clicked
信号, QAbstractButton
也是QCheckBox
的父 class。 因此,当发出clicked
信号时,它会使用默认checked
的 Boolean 参数发送,该参数指示按钮的检查 state。 对于QPushButton
,此参数始终为 False,并且在连接到信号的插槽中经常被忽略或省略。
在您的情况下发生的情况是您的getFile
function 的self
参数被checked
的参数的值填充,该参数是 boolean ,因此没有filename
属性。
此外,由于getFile
不是ApplicationWindow
class 的方法,因此它不会接收self
,因为它是默认的第一个参数,就像您调用self.getFile
。
一种解决方法是简单地将 clicked 信号分配给可以使用适当参数触发getFile
function 的中间方法。
例如
class ApplicationWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
...
open_button.clicked.connect(self.get_file)
def get_file(self):
getFile(self)
或者按照评论中的建议,您可以简单地使用 lambda 来触发 function:
open_button.clicked.connect(lambda : getFile(self))
为了清晰和可读性,我还建议更改 getFile function 的签名。
例如:
def getFile(instance):
"""this function will get the address of the sdv file location"""
instance.filename = QFileDialog.getOpenFileName(filter = "csv (*.csv)")[0]
print("File:",instance.filename)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.