Warm tip: This article is reproduced from serverfault.com, please click

Return value from button click

发布于 2015-10-13 19:41:41

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])

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() slot argument should be a callable or a signal, not 'NoneType'

Any thoughts how to make it work ?

Questioner
Viapunk
Viewed
0
Muhammad Tahir 2015-10-14 03:48:30

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)

And then,

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])

Also your

self.Button_save.clicked.connect(self.SaveTextFile(file_path))

should be

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