【问题标题】:pyqt5 python call function from another class [duplicate]来自另一个类的pyqt5 python调用函数[重复]
【发布时间】:2020-08-12 07:27:33
【问题描述】:

我正在使用 Pyqt5 构建 GUI。有一种方法可以从第二个类中定义的另一个函数调用一个类中定义的函数吗? 例如,我有我的第一堂课,我在其中定义了 GUI 的布局,并在其中放置了一些按钮和一个画布来绘制图形。 在同一个类中,我定义了连接到按钮的函数。无论如何,当我按下按钮时,我想调用另一个函数,在第二个类中定义。

头等舱

class Window(QMainWindow):
def __init__(self):
    super().__init__()

    self.title = "My_GUI"
    self.top = 100
    self.left = 100
    self.width = 1680
    self. height = 880

    self.InitWindow()

    # Definition of buttons
def InitWindow(self):

    m = PlotCanvas(self, width=5, height=4)
    m.move(300, 50)

    self.btn1 = QPushButton("execute", self)
    self.btn1.setGeometry(20, 410, 150, 50)
    self.btn1.clicked.connect(self.execute) 

def execute(self):
    PlotCanvas.plot(self)

第二个类,我定义一个 Canvas 以在按下按钮执行时更新绘图

class PlotCanvas(FigureCanvas):

    def __init__(self, parent=None, width=5, height=4, dpi=100):
       fig = Figure(figsize=(width, height), dpi=dpi)
       self.axes = fig.add_subplot(111)

       FigureCanvas.__init__(self, fig)
       self.setParent(parent)

       FigureCanvas.setSizePolicy(self,
                               QSizePolicy.Expanding,
                               QSizePolicy.Expanding)
       FigureCanvas.updateGeometry(self)
       # self.plot()

    def plot(self):
        data = [random.random() for i in range(25)]
        ax = self.figure.add_subplot(111)
        ax.plot(data, 'r-')
        self.draw()

当我运行代码时,python 崩溃。我正在使用 Pycharm

【问题讨论】:

  • PlotCanvas.plot 不是静态函数。您应该将实例声明为 self.m = PlotCanvas() 然后调用 m.plot()
  • 谢谢,但你能更好地解释一下这个过程吗?我必须在哪里声明实例 self.m = PlotCanvas 然后调用 m.plot()?
  • 明白。谢谢!不行
  • 小修改,调用plot时无需添加self。如果可行,请您接受答案。

标签: python python-3.x function canvas pyqt5


【解决方案1】:

要访问非类方法的函数,您需要创建类的实例并通过对象调用该方法。

试试这个

class Window(QMainWindow):
    def __init__(self):
        super().__init__() 
        self.title = "My_GUI"
        self.top = 100
        self.left = 100
        self.width = 1680
        self. height = 880
        self.InitWindow()
        # Definition of buttons

    def InitWindow(self):
        self.m = PlotCanvas(self, width=5, height=4)
        self.m.move(300, 50)    
        self.btn1 = QPushButton("execute", self)
        self.btn1.setGeometry(20, 410, 150, 50)
        self.btn1.clicked.connect(self.execute) 

    def execute(self):
        self.m.plot()

【讨论】:

    猜你喜欢
    • 2020-12-13
    • 2020-04-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    相关资源
    最近更新 更多