我正在使用Pyqt5构建一个图形用户界面。有没有办法从第二个类中定义的另一个函数中调用一个类中定义的函数?作为例子,我有我的第一个类,我在其中定义了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)在第二个类中,我定义了一个画布,以便在按下按钮execute时更新绘图
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
发布于 2020-04-28 21:28:37
要访问不是类方法的函数,需要创建类的实例并通过对象调用方法。
尝尝这个
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()https://stackoverflow.com/questions/61480950
复制相似问题