This (part of) code give me error:
def pickFile(self):
global imgPath01
imgPath01 = QtGui.QFileDialog.getOpenFileName(self, 'Open File', "~/", "Images (*.png *.jpg)")
print(imgPath01)
self.refreshImage()
pass
I have error on self and self.refreshImage. It says: NameError: name 'self' is not defined.
The full code can be found here.
-
That paste bin you posted has broken codeAlan Kavanagh– Alan Kavanagh2017年09月20日 09:33:36 +00:00Commented Sep 20, 2017 at 9:33
-
I know, already fixed it a bit. Just the errors above was remained..lucians– lucians2017年09月20日 09:39:54 +00:00Commented Sep 20, 2017 at 9:39
2 Answers 2
In Python, indentation matters. Those lines that aren't indented aren't part of the function, so Python tries to execute them as soon as the script is run, at which point it looks for a global variable called self, which doesn't exist.
The solution is to indent the remaining lines of the function.
Edit: Similarly, the functions you have defined aren't indented enough to be member functions of the class.
Your code should be formatted to this:
class LineDetection(QtGui.QWidget):
# ... other functions go here ...
# Note the indentation of the next line
def pickFile(self):
global imgPath01
imgPath01 = QtGui.QFileDialog.getOpenFileName(self, 'Open File', "~/", "Images (*.png *.jpg)")
print(imgPath01)
self.refreshImage()
2 Comments
Similarly, the functions you have defined aren't indented enough to be member functions of the class. This is the solution. Thanks. Can you look also at the Qt at line 206 ? Thanks again.self.refreshImage() should be indented twice as show in my edit. I don't know about the QT library, so if there's still a problem then post a separate question about that.You only need to use self as a parameter when the function is part of a class, because self is the class. When it's a normal function, you can have no parameters at all, which is what you should have done.
EDIT: after looking at the full code, I suppose the functions with the self parameter are supposed to be part of the class you define at the beginning. If so, indent them. It's necessary to do it, it's not just a choice like in many other languages: Python works this way. Be very careful with the indentation, as you might have lots of errors because of that, but FYI, Python is an interpreted language, so it does not compile and show errors before executing: it executes directly and if it finds an error it will show you that one, but no more. Review all the code.
3 Comments
the functions with the self parameter are supposed to be part of the class you define at the beginning. If so, indent them. This is it. It has to be indented also. Didn't knew about that.