我是python的新手并且学习绳索。我正在尝试使用pyQT来构建GUI,并希望能够有一个按钮,在轴上显示图形,然后是另一个按钮,在另一个轴上加载图像。我正在使用subplot。这是我尝试从搜索中获取的尝试,但它会继续打开第二个数字并为此绘制。
import sys
from PyQt4 import QtGui, QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
import matplotlib.pyplot as plt
import os
import matplotlib.cm as cm
import random
class Window(QtGui.QDialog):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
# a figure instance to plot on
self.figure = plt.figure()
# this is the Canvas Widget that displays the `figure`
# it takes the `figure` instance as a parameter to __init__
self.canvas = FigureCanvas(self.figure)
# this is the Navigation widget
# it takes the Canvas widget and a parent
self.toolbar = NavigationToolbar(self.canvas, self)
# Just some button connected to `plot` method
self.button = QtGui.QPushButton('Plot')
self.button.clicked.connect(self.plot)
self.button2 = QtGui.QPushButton('Open Image')
self.button2.clicked.connect(self.OpenImage)
self.quitButton = QtGui.QPushButton("Exit")
#self.quitButton.clicked.connect(self.Quit)
self.quitButton.clicked.connect(QtCore.QCoreApplication.instance().quit)
self.cancelButton = QtGui.QPushButton("Cancel")
self.comboBox = QtGui.QComboBox()
self.comboBox.addItem("Item 1")
self.comboBox.addItem("Item 2")
self.comboBox.addItem("Item 3")
self.txt1= QtGui.QTextEdit('Open Image')
# set the layout
#layout = QtGui.QVBoxLayout()
layout = QtGui.QGridLayout()
layout.addWidget(self.toolbar,0,0,1,5) #spans 1 row, 5 columns
layout.addWidget(self.canvas,1,0)
layout.addWidget(self.button,0,1)
layout.addWidget(self.button2,0,2)
layout.addWidget(self.quitButton,2,1)
layout.addWidget(self.cancelButton,2,2)
layout.addWidget(self.comboBox,3,2)
layout.addWidget(self.txt1,2,3)
layout.setSpacing(10)
self.setLayout(layout)
def plot(self):
''' plot some random stuff '''
# random data
data = [random.random() for i in range(10)]
# create some axes
ax = self.figure.add_subplot(231)
ax1 = self.figure.add_subplot(232)
# discards the old graph
ax.hold(False)
# plot data
ax.plot(data, '*-')
plt.grid(b=True, which='both', color='0.65',linestyle='-')
# refresh canvas
#self.canvas.draw()
#Add 2nd Graph
ax1 = self.figure.add_subplot(232)
ax1.hold(False)
# plot data
data = [random.random() for i in range(10)]
ax1.plot(data, 'r*-')
plt.grid(b=True, which='both', color='0.65',linestyle='-')
# refresh canvas
self.canvas.draw()
def OpenImage(self):
#Create some axes
ax2 = self.figure.add_subplot(233)
ax3 = self.figure.add_subplot(234)
''' Load Image from File '''
#os.chdir('c:\')
M=plt.imread('c:\Image01.tif')
# ax2 = self.figure.add_subplot(233)
ax2.hold(False)
plt.imshow(M,cmap='gray')
plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
def Quit(self):
#return app.exec()
sys.exit(app.exec_())
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
main = Window()
main.show()
sys.exit(app.exec_())