I'm very new to GUIs and I have a quick question on inheritance of variables.
In my GUI i have two buttons, one selects an xlsx file, the other graphs it. The first class
below sets the buttons and selects the file:
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
vBoxLayout = QtGui.QVBoxLayout(self)
file_btn = QtGui.QPushButton('Select File', self)
file_btn.clicked.connect(self.get_graph_file)
graphing_btn = QtGui.QPushButton('Plot Graph', self)
graphing_btn.clicked.connect(Plotting_Graph)
self.show()
def get_graph_file(self):
fname_graphfile = QtGui.QFileDialog.getOpenFileName(self, 'Open file', '/Users/.../', 'excel files (*.xlsx)')
... and the second should inherit fname_graphfile
and graph it (I've only added in a bit of the graphing code)...
class Plotting_Graph(Example):
def __init__(self):
self.PlottingGraph()
def PlottingGraph(self):
xl = ef(fname_graphfile[0])......
When run, it gives an error global name 'fname_graphfile' is not defined
.
How do I get the second class
to remember something I've defined in the previous class
?
fname_graphfile
is a local variable in the get_graph_file
so other methods don't have access to it what you should do is make it an instance attribute so it can be accessed from any method and then add an argument to Plotting_Graph.PlottingGraph
that accepts the xlsx
file as a parameter to the method and pass self.fname_graphfile
to it from the button click
your final code should look like this
from PyQt4 import QtCore, QtGui
import sys
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.fname_graph_file = ''
file_btn = QtGui.QPushButton('Select File', self)
file_btn.setGeometry(100, 100, 150, 30)
file_btn.clicked.connect(self.get_graph_file)
graphing_btn = QtGui.QPushButton('Plot Graph', self)
plot = Plotting_Graph()
graphing_btn.clicked.connect(lambda: plot.PlottingGraph(self.fname_graph_file))
self.show()
def get_graph_file(self):
self.fname_graph_file = QtGui.QFileDialog.getOpenFileName(self, 'Open file', '/home', 'excel files (*.xlsx)')
class Plotting_Graph(Example):
def __init__(self):
pass
def PlottingGraph(self, fname_graphfile):
print(fname_graphfile)
# xl = ef(fname_graphfile[0])
app = QtGui.QApplication([])
a = Example()
app.exec_()