我很想从单击PyQt中的按钮时调用的函数返回值.这就是我想为变量添加值的方式:
file_path = self.Button_open.clicked.connect(self.OpenTextFile)
整个功能如下:
def OpenTextFile(self):
dialog = QtGui.QFileDialog()
dialog.setWindowTitle("Choose a file to open")
dialog.setFileMode(QtGui.QFileDialog.ExistingFile)
dialog.setNameFilter("Text (*.txt);; All files (*.*)")
dialog.setViewMode(QtGui.QFileDialog.Detail)
filename = QtCore.QStringList()
if(dialog.exec_()):
file_name = dialog.selectedFiles()
plain_text = open(file_name[0]).read()
self.Editor.setPlainText(plain_text)
return str(file_name[0])
现在,当我想将file_path传递给另一个函数时,python解释器说
self.Button_save.clicked.connect(self.SaveTextFile(file_path))
TypeError: connect() slot argument should be a callable or a signal, not ‘NoneType’
有什么想法使它起作用吗?
解决方法:
将file_path存储在类级别的变量中,然后在您的按钮click方法中更新该值.
self.file_path = None
self.Button_open.clicked.connect(self.OpenTextFile)
接着,
def OpenTextFile(self):
dialog = QtGui.QFileDialog()
dialog.setWindowTitle("Choose a file to open")
dialog.setFileMode(QtGui.QFileDialog.ExistingFile)
dialog.setNameFilter("Text (*.txt);; All files (*.*)")
dialog.setViewMode(QtGui.QFileDialog.Detail)
filename = QtCore.QStringList()
if(dialog.exec_()):
file_name = dialog.selectedFiles()
plain_text = open(file_name[0]).read()
self.Editor.setPlainText(plain_text)
self.file_path = str(file_name[0])
还有你的
self.Button_save.clicked.connect(self.SaveTextFile(file_path))
应该
self.Button_save.clicked.connect(self.SaveTextFile)
然后在您的保存点击方法中
def SaveTextFile(self):
save(self.file_path) # Your code to save file