按钮点击返回值 [英] Return value from button click
问题描述
当我在 PyQt 中单击按钮时,我很难从函数中返回一个值.这就是我想为变量赋值的方式:
I struggled with returning a value from function which is invoked when I click button in PyQt. That's how I'd like to put a value to the variable:
file_path = self.Button_open.clicked.connect(self.OpenTextFile)
整个函数看起来像这样:
Whole function looks like this:
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 解释器说
Now, when I want to pass the file_path to the other function, python interpreter says
self.Button_save.clicked.connect(self.SaveTextFile(file_path))类型错误:connect() 槽参数应该是可调用的或信号,而不是NoneType"
self.Button_save.clicked.connect(self.SaveTextFile(file_path)) TypeError: connect() slot argument should be a callable or a signal, not 'NoneType'
任何想法如何使它工作?
Any thoughts how to make it work ?
推荐答案
将 file_path 存储在类级别变量中,并在按钮单击方法中更新该值.
Store the file_path in a class level variable and update that value in your button click method.
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)
并在您的保存点击方法中
and in your save click method
def SaveTextFile(self):
save(self.file_path) # Your code to save file
这篇关于按钮点击返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!