【问题标题】:Python QtGui: inheritance of variables between classesPython QtGui:类之间变量的继承
【发布时间】:2016-04-11 07:10:20
【问题描述】:

我对 GUI 很陌生,我有一个关于变量继承的快速问题。

在我的 GUI 中,我有两个按钮,一个选择一个 xlsx 文件,另一个选择它。下面的第一个class 设置按钮并选择文件:

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

...第二个应该继承fname_graphfile 并绘制它(我只添加了一点图形代码)...

class Plotting_Graph(Example):

def __init__(self):

    self.PlottingGraph()

def PlottingGraph(self):

    xl = ef(fname_graphfile[0])......

运行时会报错global name 'fname_graphfile' is not defined

如何让第二个 class 记住我在前一个 class 中定义的内容?

【问题讨论】:

    标签: python class inheritance qtgui


    【解决方案1】:

    fname_graphfileget_graph_file 中的局部变量,因此其他方法无法访问它,您应该将其设为实例属性,以便可以从任何方法访问它,然后将参数添加到 @ 987654323@ 接受 xlsx 文件作为方法的参数,并通过单击按钮将 self.fname_graphfile 传递给它

    您的最终代码应如下所示

    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_()
    

    【讨论】:

      猜你喜欢
      • 2013-02-11
      • 2018-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-25
      • 2021-04-10
      • 2012-11-04
      • 1970-01-01
      相关资源
      最近更新 更多