I've got this pro开发者_开发技巧blem with a project that involves programming in Python. I made this class with which a screen pops up and so allowing me to open a xls file. Inside this class the directory to this file is then put into this variable 'filename'. :>
class OpenFile(QtGui.QMainWindow):
def __init__(self):
super(OpenFile, self).__init__()
self.initUI()
def initUI(self):
openFile = QtGui.QPushButton('Open Orderpakket', self)
openFile.setGeometry(0, 00, 350, 300)
openFile.setStatusTip('Open new File')
self.connect(openFile, QtCore.SIGNAL('clicked()'), self.showDialog)
self.setWindowTitle('Open Orderpakket')
def showDialog(self):
filename = QtGui.QFileDialog.getOpenFileName(self, 'Open file',r'J:\Integratie Project\Files', "Excel Files (*.xls*.xlsx)")
print filename
Inside this class the variable filename indeed has the correct directory inside it. Now i want to use it here, outsite a class or a def:
wb = xlrd.open_workbook(filename)
That doesn't work, giving me the error that 'filename is not defined'
I've read about the 'global' command of Python which seems to have the solution, but i can't seem to get that working.
Anyone?
I will not get into details of your code, but will use it only to explain the basic concepts.
The variable filename
in showDialog
is defined as a local variable - hence, you cannot access it outside this function.
If you want to define the variable as an instance variable for the class OpenFile, you need to use self.filename
.
I assume you have somewhere an instance of the class OpenFile
, such as:
openfile = OpenFile()
Now you can access the variable from this instance by invoking:
openfile.filename
Add filename
as an attribute to the object of your class, i.e. self
:
self.filename = QtGui.QFileDialog.getOpenFileName(self, 'Open file',r'J:\Integratie Project\Files', "Excel Files (*.xls *.xlsx)")
This way you can access it like that:
wb = xlrd.open_workbook(openfile.filename)
where openfile
is an object of OpenFile
class.
精彩评论