单击按钮返回值 [英] 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)
整个功能如下:
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)) TypeError: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存储在类级别变量中,并在按钮click方法中更新该值.
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屋!