本文整理汇总了Python中matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg.mpl_connect方法的典型用法代码示例。如果您正苦于以下问题:Python FigureCanvasQTAgg.mpl_connect方法的具体用法?Python FigureCanvasQTAgg.mpl_connect怎么用?Python FigureCanvasQTAgg.mpl_connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg
的用法示例。
在下文中一共展示了FigureCanvasQTAgg.mpl_connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: MPLibWidget
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import mpl_connect [as 别名]
class MPLibWidget(QtWidgets.QWidget):
"""
base MatPlotLib widget
"""
def __init__(self, parent=None):
super(MPLibWidget, self).__init__(parent)
self.figure = Figure()
self.canvas = FigureCanvasQTAgg(self.figure)
self.canvas.setParent(self)
self.mpl_toolbar = NavigationToolbar2QT(self.canvas, self)
self.canvas.mpl_connect('key_press_event', self.on_key_press)
self.axes = self.figure.add_subplot(111)
# self.axes.hold(False)
self.compute_initial_figure()
self.layoutVertical = QtWidgets.QVBoxLayout(self)
self.layoutVertical.addWidget(self.canvas)
self.layoutVertical.addWidget(self.mpl_toolbar)
def on_key_press(self, event):
"""not working"""
print('you pressed', event.key)
# implement the default mpl key press events described at
# http://matplotlib.org/users/navigation_toolbar.html#navigation-keyboard-shortcuts
key_press_handler(event, self.canvas, self.mpl_toolbar)
def compute_initial_figure(self):
pass
示例2: QFigureWidget
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import mpl_connect [as 别名]
class QFigureWidget(QtWidgets.QWidget):
"""Widget to layout the actual figure and toolbar. Further it forwards.
the key press events from the widget to the figure."""
def __init__(self, fig, *args, **kw):
super(QFigureWidget, self).__init__(*args, **kw)
self.fig = fig
self.canvas = FigureCanvasQTAgg(self.fig)
self.canvas.setParent(self)
self.canvas.setFocusPolicy(QtCore.Qt.StrongFocus)
self.canvas.setFocus()
color = fig.get_facecolor()
self.toolbar = QNavigationToolbar(self.canvas, self)
self.toolbar.setStyleSheet("QNavigationToolbar { background-color: %s }"
%rgb2hex(color))
self.toolbar.setIconSize(QtCore.QSize(16, 16))
self.canvas.mpl_connect('key_press_event', self.on_key_press)
vbox = QtWidgets.QVBoxLayout(self)
vbox.addWidget(self.canvas)
vbox.addWidget(self.toolbar)
vbox.setContentsMargins(0, 0, 0, 0)
vbox.setSpacing(0)
def hideToolbar(self):
self.toolbar.hide()
def showToolbar(self):
self.toolbar.show()
def close(self):
super(QFigureWidget, self).close()
def on_key_press(self, event):
# sometimes mpl has a weird ideas what oo-programing is.
# any could overwrite method by my self
# no fullscreen unless self is a window!
if event.key == "t":
self.toolbar.toggle()
elif event.key not in rcParams["keymap.fullscreen"]:
key_press_handler(event, self.canvas, self.toolbar)
示例3: __createMatplotlibCanvas
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import mpl_connect [as 别名]
def __createMatplotlibCanvas(self, plt_extent):
fig = Figure(#figsize=(1, 1),
#tight_layout=True,
linewidth=0.0,
subplotpars=matplotlib.figure.SubplotParams(left=0,
bottom=0,
right=1,
top=1,
wspace=0,
hspace=0
)
)
#fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None)
#fig = Figure((24, 24), tight_layout=True)
# try:
# fig = Figure(tight_layout=True)
# except:
# #tight layout not available
# fig = Figure()
#fig = plt.figure()
#fig.set_tight_layout(True)
#font = {"family": "arial", "weight": "normal", "size": 12}
#rc("font", **font)
rect = fig.patch
rect.set_facecolor((0.9, 0.9, 0.9))
# self.subplot = fig.add_axes(
# #(0.08, 0.15, 0.92, 0.82),
# (0.0, 0.0, 1.0, 1.0),
# anchor="SW",
# adjustable="box-forced"
# )
#left bottom right top
self.subplot = fig.add_axes(
(LEFT_MARGIN, BOTTOM_MARGIN, RIGHT_MARGIN, TOP_MARGIN),
adjustable="datalim",
aspect=1
)
#self.subplot.plot.tight_layout(True)
self.subplot.set_xbound(plt_extent.xmin, plt_extent.xmax)
self.subplot.set_ybound(plt_extent.ymin, plt_extent.ymax)
self.__setupAxes(self.subplot)
#fig.tight_layout()
canvas = FigureCanvasQTAgg(fig)
sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
canvas.setSizePolicy(sizePolicy)
canvas.mpl_connect("pick_event", self.__plotPicked)
canvas.mpl_connect("draw_event", self.__figureDrawn)
canvas.mpl_connect("button_press_event", self.__buttonPressed)
canvas.mpl_connect("motion_notify_event", self.__mouse_move)
return canvas
示例4: Window
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import mpl_connect [as 别名]
class Window(QDialog):
def __init__(self, params_object, library_object, group, parent=None):
QDialog.__init__(self, parent)
self.params = params_object
self.library = library_object
self.group = group
matplotlib.projections.register_projection(My_Axes)
self.region_colors = {0:'gray', 1:'red', 2:'green', 3:'orange', 4:'teal', 5:'pink',
6:'cyan', 7:'magenta', 8:'gold'}
if self.group == 'ALL':
self.plural_group = "s"
else:
self.plural_group = ""
self.setWindowTitle("NMRmix: Peaks Histogram for %s Group%s" % (self.group, self.plural_group))
self.scale = 1.05
self.setAttribute(Qt.WA_DeleteOnClose, True)
self.createMainFrame()
def createMainFrame(self):
self.fig = plt.gcf()
self.fig.patch.set_facecolor('white')
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self)
self.canvas.setFocusPolicy(Qt.StrongFocus)
self.canvas.setFocus()
self.canvas.setMinimumHeight(100)
self.canvas.setMinimumWidth(100)
self.mpl_toolbar = NavigationToolbar2(self.canvas, self)
self.mpl_toolbar.hide()
self.mpl_toolbar.pan()
self.canvas.mpl_connect('scroll_event', self.zooming)
ins = "Left-click+drag to pan x-axis / Right-click+drag to zoom x-axis"
self.instructionLabel = QLabel(ins)
self.instructionLabel.setStyleSheet('QLabel{qproperty-alignment: AlignCenter; font-size: 12px;}')
self.showignoredregionsCheckBox = QCheckBox("Show Ignored Regions")
self.showignoredregionsCheckBox.setChecked(True)
self.showignoredregionsCheckBox.setToolTip("Tooltip") # TODO: Tooltip
self.showignoredregionsCheckBox.stateChanged.connect(self.handleIgnored)
self.closeButton = QPushButton("Close")
self.closeButton.setStyleSheet("QPushButton{color: red; font-weight: bold;}")
self.closeButton.clicked.connect(self.closeEvent)
self.saveButton = QPushButton("Save")
self.saveButton.setStyleSheet("QPushButton{color: green; font-weight: bold;}")
self.saveButton.clicked.connect(self.saveResults)
self.resetButton = QPushButton("Reset")
self.resetButton.setStyleSheet("QPushButton{color: blue; font-weight: bold;}")
self.resetButton.clicked.connect(self.resetGraph)
self.calculateAllHistogram()
self.calculateIntenseHistogram()
self.drawIgnoredRegions()
winLayout = QVBoxLayout(self)
winLayout.addWidget(self.canvas)
winLayout.addWidget(self.instructionLabel)
winLayout.addWidget(self.showignoredregionsCheckBox)
buttonLayout = QHBoxLayout()
buttonLayout.addWidget(self.closeButton)
buttonLayout.addWidget(self.resetButton)
buttonLayout.addWidget(self.saveButton)
winLayout.addLayout(buttonLayout)
winLayout.setAlignment(self.showignoredregionsCheckBox, Qt.AlignCenter)
self.fig.tight_layout(pad=3)
self.canvas.draw()
def calculateAllHistogram(self):
self.ax1 = self.fig.add_subplot(211, projection="My_Axes")
self.ax1.set_title("Peaks Histogram for %s Group%s" % (self.group, self.plural_group), fontweight='bold')
self.ax1.set_xlabel("Chemical Shift (ppm)", fontweight='bold')
self.ax1.set_ylabel("Number of Peaks", fontweight='bold')
data = list(self.library.stats[self.group]['Peaklist'])
y, binEdges = np.histogram(data, bins=np.arange(-1, 12, 0.02))
bincenters = 0.5 * (binEdges[1:] + binEdges[:-1])
self.ax1.set_xlim(self.params.shift_range[self.params.nuclei])
self.upper_ylim_all = max(y)+(math.ceil(max(y)*0.05))
self.ax1.set_ylim([0, self.upper_ylim_all])
self.ax1.plot(bincenters, y, '-', color='blue')
def calculateIntenseHistogram(self):
self.ax2 = self.fig.add_subplot(212, sharex=self.ax1, projection="My_Axes")
self.ax2.set_title("Intense Peaks Histogram for %s Group%s" % (self.group, self.plural_group),
fontweight='bold')
self.ax2.set_xlabel("Chemical Shift (ppm)", fontweight='bold')
self.ax2.set_ylabel("Number of Peaks", fontweight='bold')
data = list(self.library.stats[self.group]['Intense Peaklist'])
y, binEdges = np.histogram(data, bins=np.arange(-1, 12, 0.02))
bincenters = 0.5 * (binEdges[1:] + binEdges[:-1])
self.ax2.set_xlim([12, -1])
self.upper_ylim_intense = max(y)+(math.ceil(max(y)*0.05))
self.ax2.set_ylim([0, self.upper_ylim_intense])
self.ax2.plot(bincenters, y, '-', color='purple')
def resetGraph(self):
self.mpl_toolbar.home()
def drawIgnoredRegions(self):
groups = ['ALL']
if self.group != 'ALL':
groups.append(self.group)
for region in self.library.ignored_regions:
#.........这里部分代码省略.........
示例5: __init__
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import mpl_connect [as 别名]
class FigureTab:
cursors = [15000, 45000]
colors = ['orange', 'violet']
def __init__(self, layout, vna):
# create figure
self.figure = Figure()
if sys.platform != 'win32':
self.figure.set_facecolor('none')
self.canvas = FigureCanvas(self.figure)
layout.addWidget(self.canvas)
# create navigation toolbar
self.toolbar = NavigationToolbar(self.canvas, None, False)
self.toolbar.layout().setSpacing(6)
# remove subplots action
actions = self.toolbar.actions()
if int(matplotlib.__version__[0]) < 2:
self.toolbar.removeAction(actions[7])
else:
self.toolbar.removeAction(actions[6])
self.toolbar.addSeparator()
self.cursorLabels = {}
self.cursorValues = {}
self.cursorMarkers = {}
self.cursorPressed = {}
for i in range(len(self.cursors)):
self.cursorMarkers[i] = None
self.cursorPressed[i] = False
self.cursorLabels[i] = QLabel('Cursor %d, kHz' % (i + 1))
self.cursorLabels[i].setStyleSheet('color: %s' % self.colors[i])
self.cursorValues[i] = QSpinBox()
self.cursorValues[i].setMinimumSize(90, 0)
self.cursorValues[i].setSingleStep(10)
self.cursorValues[i].setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter)
self.toolbar.addWidget(self.cursorLabels[i])
self.toolbar.addWidget(self.cursorValues[i])
self.cursorValues[i].valueChanged.connect(partial(self.set_cursor, i))
self.canvas.mpl_connect('button_press_event', partial(self.press_marker, i))
self.canvas.mpl_connect('motion_notify_event', partial(self.move_marker, i))
self.canvas.mpl_connect('button_release_event', partial(self.release_marker, i))
self.toolbar.addSeparator()
self.plotButton = QPushButton('Rescale')
self.toolbar.addWidget(self.plotButton)
layout.addWidget(self.toolbar)
self.plotButton.clicked.connect(self.plot)
self.mode = None
self.vna = vna
def add_cursors(self, axes):
if self.mode == 'gain_short' or self.mode == 'gain_open':
columns = ['Freq., kHz', 'G, dB', r'$\angle$ G, deg']
else:
columns = ['Freq., kHz', 'Re(Z), \u03A9', 'Im(Z), \u03A9', '|Z|, \u03A9', r'$\angle$ Z, deg', 'SWR', r'|$\Gamma$|', r'$\angle$ $\Gamma$, deg', 'RL, dB']
y = len(self.cursors) * 0.04 + 0.01
for i in range(len(columns)):
self.figure.text(0.19 + 0.1 * i, y, columns[i], horizontalalignment = 'right')
self.cursorRows = {}
for i in range(len(self.cursors)):
y = len(self.cursors) * 0.04 - 0.03 - 0.04 * i
self.figure.text(0.01, y, 'Cursor %d' % (i + 1), color = self.colors[i])
self.cursorRows[i] = {}
for j in range(len(columns)):
self.cursorRows[i][j] = self.figure.text(0.19 + 0.1 * j, y, '', horizontalalignment = 'right')
if self.mode == 'smith':
self.cursorMarkers[i], = axes.plot(0.0, 0.0, marker = 'o', color = self.colors[i])
else:
self.cursorMarkers[i] = axes.axvline(0.0, color = self.colors[i], linewidth = 2)
self.set_cursor(i, self.cursorValues[i].value())
def set_cursor(self, index, value):
FigureTab.cursors[index] = value
marker = self.cursorMarkers[index]
if marker is None: return
row = self.cursorRows[index]
freq = value
gamma = self.vna.gamma(freq)
if self.mode == 'smith':
marker.set_xdata(gamma.real)
marker.set_ydata(gamma.imag)
else:
marker.set_xdata(freq)
row[0].set_text('%d' % freq)
if self.mode == 'gain_short':
gain = self.vna.gain_short(freq)
magnitude = 20.0 * np.log10(np.absolute(gain))
angle = np.angle(gain, deg = True)
row[1].set_text(unicode_minus('%.1f' % magnitude))
row[2].set_text(unicode_minus('%.1f' % angle))
elif self.mode == 'gain_open':
gain = self.vna.gain_open(freq)
magnitude = 20.0 * np.log10(np.absolute(gain))
angle = np.angle(gain, deg = True)
row[1].set_text(unicode_minus('%.1f' % magnitude))
row[2].set_text(unicode_minus('%.1f' % angle))
else:
swr = self.vna.swr(freq)
z = self.vna.impedance(freq)
rl = 20.0 * np.log10(np.absolute(gamma))
if rl > -0.01: rl = 0.0
row[1].set_text(metric_prefix(z.real))
#.........这里部分代码省略.........
示例6: Main
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import mpl_connect [as 别名]
#.........这里部分代码省略.........
dname = dirDialog.getSaveFileName(self, 'Save model to files split by components',defDirName)
dname = str(dname[0])
if dname != '':
joebvpfit.writeVPmodelByComp(dname, self.spectrum,self.fitpars)
def addLineDialog(self):
dlgOutput=newLineDialog.get_newline()
if (dlgOutput != 0):
if '' not in dlgOutput:
newlam,newz,newcol,newb,newvel,newvel1,newvel2 = dlgOutput
self.datamodel.addLine(self.wave,float(newlam), float(newz), float(newcol), float(newb), float(newvel), float(newvel1), float(newvel2)) #dialog=newLineDialog(parent=None)
self.fitpars = self.datamodel.fitpars
self.fiterrors = self.datamodel.fiterrors
self.parinfo = self.datamodel.parinfo
self.tableView.setModel(self.datamodel)
def updateplot(self):
if self.wave1==None: waveidx1=0 # Default to plotting entire spectrum for now
else: waveidx1=jbg.closest(self.wave,self.wave1)
wlen=len(self.spectrum.wavelength)/self.numchunks
for i,sp in enumerate(self.spls):
sp.clear()
prange=range(waveidx1+i*wlen,waveidx1+(i+1)*wlen)
if ((len(self.fitpars[0])>0)):
sp.plot(self.wave,self.normflux,linestyle='steps-mid')
if self.pixtog==1:
sp.plot(self.wave[cfg.fitidx], self.normflux[cfg.fitidx], 'gs', markersize=4, mec='green')
model=joebvpfit.voigtfunc(self.wave,self.fitpars)
res=self.normflux-model
sp.plot(self.wave,model,'r')
if self.restog==1:
sp.plot(self.wave,-res,'.',color='black', ms=2)
sp.plot(self.wave,[0]*len(self.wave),color='gray')
### label lines we are trying to fit
if self.labeltog==1:
for j in range(len(self.fitpars[0])):
labelloc=self.fitpars[0][j]*(1.+self.fitpars[3][j])+self.fitpars[4][j]/c*self.fitpars[0][j]*(1.+self.fitpars[3][j])
label = ' {:.1f}_\nz{:.4f}'.format(self.fitpars[0][j], self.fitpars[3][j])
sp.text(labelloc, cfg.label_ypos, label, rotation=90, withdash=True, ha='center', va='bottom', clip_on=True, fontsize=cfg.label_fontsize)
sp.plot(self.wave,self.normsig,linestyle='steps-mid',color='red', lw=0.5)
sp.plot(self.wave,-self.normsig,linestyle='steps-mid',color='red', lw=0.5)
sp.set_ylim(cfg.ylim)
sp.set_xlim(self.wave[prange[0]],self.wave[prange[-1]])
sp.set_xlabel('wavelength (A)', fontsize=cfg.xy_fontsize, labelpad=cfg.x_labelpad)
sp.set_ylabel('normalized flux', fontsize=cfg.xy_fontsize, labelpad=cfg.y_labelpad)
sp.get_xaxis().get_major_formatter().set_scientific(False)
sp.get_xaxis().get_major_formatter().set_useOffset(False)
self.changefig(self.fig)
def changefig(self, item):
#text = str(item.text())
self.rmmpl()
self.addmpl(self.fig)
def changesidefig(self, item):
#text = str(item.text())
self.rmsidempl()
self.addsidempl(self.sidefig)
def on_click(self, event):
self.lastclick=event.xdata
self.sideplot(self.lastclick)
def addmpl(self, fig):
self.canvas = FigureCanvas(fig)
self.canvas.mpl_connect('button_press_event',self.on_click)
self.mplvl.addWidget(self.canvas)
self.canvas.draw()
self.toolbar = NavigationToolbar(self.canvas,self.mplwindow,coordinates=True)
self.mplvl.addWidget(self.toolbar)
def addsidempl(self, sidefig):
self.sidecanvas = FigureCanvas(sidefig)
self.sidecanvas.setParent(self.sideMplWindow)
if len(self.sidefig.axes) == 0:
self.sidemplvl = QVBoxLayout()
if len(self.sidefig.axes) != 0:
self.sidemplvl.addWidget(self.sidecanvas)
if len(self.sidefig.axes) == 0:
self.sideMplWindow.setLayout(self.sidemplvl)
self.sidecanvas.draw()
def rmmpl(self,):
self.mplvl.removeWidget(self.canvas)
self.canvas.close()
self.mplvl.removeWidget(self.toolbar)
self.toolbar.close()
def rmsidempl(self, ):
self.sidemplvl.removeWidget(self.sidecanvas)
self.sidecanvas.close()
示例7: __init__
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import mpl_connect [as 别名]
def __init__(self, parent=None, width=5, height=4, dpi=100):
self.press = None
self.prevX = 0
self.ydata = list()
self.xdata = list()
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)
self.axes.hold(True)
#self.compute_initial_figure()
#
FigureCanvas.__init__(self, fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self,
QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
FigureCanvas.mpl_connect(self,'button_press_event', self.onclick)
FigureCanvas.mpl_connect(self, 'button_release_event', self.onrelease)
FigureCanvas.mpl_connect(self, 'motion_notify_event', self.onmove)
FigureCanvas.mpl_connect(self, 'scroll_event', self.zoom)
FigureCanvas.mpl_connect(self, 'pick_event', self.onpick)
FigureCanvas.mpl_connect(self, 'figure_enter_event', self.on_enter)
FigureCanvas.mpl_connect(self, 'figure_exit_event', self.on_exit)
示例8: CustomPlot
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import mpl_connect [as 别名]
class CustomPlot(QDialog):
"""
Class used to create a plot window
Data is read from session object
"""
_colors = ['#FF0000', '#0000FF', '#00FF00', '#00002C', '#FF1AB9',
'#FFD300', '#005800', '#8484FF', '#9E4F46', '#00FFC1',
'#008495', '#00007B', '#95D34F', '#F69EDC', '#D312FF']
def __init__(self, parent, session):
"""
Create plot window
:param parent: Parent window object
:param session: Session object to plot data from
"""
super(CustomPlot, self).__init__(parent)
self.amp = []
self.peak_time = []
self.fwhm = []
self.regular = []
self.smooth = []
self.sem = []
self.scroll = 3
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.used_colors = []
self.session = session
self.fig = plt.figure()
self.current_ax = self.fig.add_subplot(111)
self.axes = {}
self.ax_list = []
self.add_ax(self.current_ax)
self.ui.toolButton_anatomy.hide()
if session.anatomy is not None:
self.ui.toolButton_anatomy.show()
self.canvas = FigureCanvas(self.fig)
self.toolbar = NavigationToolbar(self.canvas, self, coordinates=True)
self.toolbar.hide()
self.ui.mplvl.addWidget(self.canvas)
self.ui.checkBox_fwhm.clicked.connect(self.plot_fwhm)
self.ui.checkBox_sem.clicked.connect(self.plot_sem)
self.ui.checkBox_regular.clicked.connect(self.replot)
self.ui.checkBox_smooth.clicked.connect(self.replot)
self.ui.checkBox_amp.clicked.connect(self.plot_amplitude)
self.ui.checkBox_peak.clicked.connect(self.plot_peak)
self.ui.stimuliBox.currentTextChanged.connect(self.replot)
self.ui.mean_response_btn.clicked.connect(self.replot)
self.ui.several_responses_btn.clicked.connect(self.replot)
self.ui.checkBox_labels.clicked.connect(self.show_legends)
self.ui.label_size.valueChanged.connect(self.show_legends)
self.ui.spinBox.valueChanged.connect(self.replot)
self.ui.toolButton_home.clicked.connect(self.toolbar.home)
self.ui.toolButton_export.clicked.connect(self.tool_export)
self.ui.toolButton_pan.clicked.connect(self.toolbar.pan)
self.ui.toolButton_zoom.clicked.connect(self.toolbar.zoom)
self.ui.toolButton_anatomy.clicked.connect(self.tool_anatomy)
self.setWindowTitle('Plot - ' + session.name)
self.export_window = None
self.add_stimuli_types()
# Enable the 'plot several' button if the object has more than 1 child
children = self.session.children + self.session.sessions
if children and len(children) > 1:
self.ui.several_responses_btn.setEnabled(True)
else:
self.ui.several_responses_btn.hide()
self.ui.toolButton_add_subplot.clicked.connect(self.add_subplot)
self.ui.toolButton_rem_subplot.clicked.connect(self.remove_subplot)
# Move the subplot to make space for the legend
self.fig.subplots_adjust(right=0.8)
self.canvas.mpl_connect('button_press_event', self.click_plot)
self.fig.tight_layout(pad=2.0)
# Change default value in smooth wheel if percent is used
if self.session.get_setting("percent"):
self.ui.spinBox.setValue(2)
self.replot()
self.show()
self.ui.verticalLayout_3.update()
#.........这里部分代码省略.........
示例9: MplGraphQt5Widget
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import mpl_connect [as 别名]
class MplGraphQt5Widget(QWidget):
def __init__(self, parent=None):
super(MplGraphQt5Widget, self).__init__(parent)
self.width = 3
self.height = 3
self.dpi = 100
self._dataY = np.array([])
self._dataX = np.array([])
self._spCols = 1
self._spRows = 1
self.all_sp_axes = []
self.fig = Figure(figsize=(self.width, self.height), dpi=self.dpi)
self.all_sp_axes.append(self.fig.add_subplot(self._spCols, self._spRows, 1))
self.fig.set_frameon(False)
self.fig.set_tight_layout(True)
self.canvas = Canvas(self.fig)
self._navBarOn = False
self.mpl_toolbar = NavigationToolbar(self.canvas, parent)
self.mpl_toolbar.dynamic_update()
self.canvas.mpl_connect('key_press_event', self.on_key_press)
self.canvas.mpl_connect('button_press_event', self.on_button_press)
self.canvas.mpl_connect('motion_notify_event', self.on_mouse_move)
self.canvas.setFocusPolicy(Qt.ClickFocus)
self.canvas.setFocus()
self.canvas.setParent(parent)
self.canvas.clearMask()
self.canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.canvas.updateGeometry()
vbox = QVBoxLayout()
vbox.addWidget(self.canvas)
vbox.addWidget(self.mpl_toolbar)
if not self._navBarOn:
self.mpl_toolbar.hide()
self.setLayout(vbox)
def get_icon(name):
"""Return Matplotlib icon *name*"""
return QIcon(osp.join(rcParams['datapath'], 'images', name))
key_pressed = pyqtSignal(object, name='keyPressed')
def on_key_press(self, event):
self.key_pressed.emit(event)
key_press_handler(event, self.canvas, self.mpl_toolbar)
button_pressed = pyqtSignal(object, name='buttonPressed')
def on_button_press(self, event):
self.button_pressed.emit(event)
key_press_handler(event, self.canvas, self.mpl_toolbar)
mouse_move = pyqtSignal(object, name='mouseMoved')
def on_mouse_move(self, event):
self.mouse_move.emit(event)
key_press_handler(event, self.canvas, self.mpl_toolbar)
def generateNewAxes(self):
for ax in self.all_sp_axes:
self.fig.delaxes(ax)
self.all_sp_axes = []
numOfAxes = (self._spRows*self._spCols)+1
for i in np.arange(1,numOfAxes):
self.all_sp_axes.append(self.fig.add_subplot(self._spRows, self._spCols, i))
self.canvas.setGeometry(100, 100, 300, 300) #Used to update the new number of axes
self.canvas.updateGeometry() #This will bring the size of the canvas back to the original (defined by the vbox)
spRowsChanged = pyqtSignal(int)
def getspRows(self):
return self._spRows
@pyqtSlot(int)
def setspRows(self, spRows):
self._spRows = spRows
self.generateNewAxes()
self.spRowsChanged.emit(spRows)
def resetspRows(self):
self.setspRows(1)
spRows = pyqtProperty(int, getspRows, setspRows, resetspRows)
spColsChanged = pyqtSignal(int)
def getspCols(self):
return self._spCols
#.........这里部分代码省略.........
示例10: AppForm
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import mpl_connect [as 别名]
#.........这里部分代码省略.........
# alpha=0.44,
# picker=5)
#self.data = int(self.textbox.text())
#x = np.random.standard_normal(self.data)
#y = 2.0 + 3.0 * x + 4.0 * np.random.standard_normal(self.data)
#self.axes.hexbin(x,y)
self.nevent = int(self.textbox.text())
self.pd.simulate(self.nevent)
self.axes.imshow(self.pd.pixelevent[self.nevent-1])
self.canvas.draw()
def create_main_frame(self):
self.main_frame = QWidget()
# Create the mpl Figure and FigCanvas objects.
# 5x4 inches, 100 dots-per-inch
#
self.dpi = 100
self.fig = Figure((5.0, 4.0), dpi=self.dpi)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self.main_frame)
# Since we have only one plot, we can use add_axes
# instead of add_subplot, but then the subplot
# configuration tool in the navigation toolbar wouldn't
# work.
#
self.axes = self.fig.add_subplot(111)
# Bind the 'pick' event for clicking on one of the bars
#
self.canvas.mpl_connect('pick_event', self.on_pick)
# Create the navigation toolbar, tied to the canvas
#
self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)
# Other GUI controls
#
self.textbox = QLineEdit()
self.textbox.setMinimumWidth(200)
self.textbox.editingFinished.connect(self.on_draw)
self.draw_button = QPushButton("&Draw")
self.draw_button.clicked.connect(self.on_draw)
self.grid_cb = QCheckBox("Show &Grid")
self.grid_cb.setChecked(False)
self.grid_cb.stateChanged.connect(self.on_draw) #int
slider_label = QLabel('Bar width (%):')
self.slider = QSlider(Qt.Horizontal)
self.slider.setRange(1, 100)
self.slider.setValue(20)
self.slider.setTracking(True)
self.slider.setTickPosition(QSlider.TicksBothSides)
self.slider.valueChanged.connect(self.on_draw)#int
#
# Layout with box sizers
#
hbox = QHBoxLayout()
示例11: Window
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import mpl_connect [as 别名]
#.........这里部分代码省略.........
self.smilesLabel = QLabel("<b>SMILES:</b> Unknown")
self.molformulaLabel = QLabel("<b>Mol. Formula:</b> Unknown")
self.molwtLabel = QLabel("<b>Mol. Weight:</b> Unknown")
self.structure.setText("No Structure Available")
self.structure.setAlignment(Qt.AlignCenter)
self.editinfoButton = QPushButton('Edit Compound Info')
self.editinfoButton.setToolTip("Opens a window to edit compound information") # TODO: Set tooltip
self.restoreinfoButton = QPushButton('Restore Compound Info')
self.restoreinfoButton.setToolTip("Resets compound information to original imported values") # TODO: Set tooltip
self.savestructureButton = QPushButton('Save Structure Image')
self.savestructureButton.setToolTip("Tooltip") # TODO: Set tooltip
def initSpectrum(self):
# Compound Spectrum Tab
matplotlib.projections.register_projection(My_Axes)
self.scale = 1.05
self.show_ignored = True
self.show_ignored_peaks = True
self.compoundtab2 = QWidget()
self.compoundtab2.setStyleSheet("QWidget{background-color: white;}")
self.fig = plt.gcf()
self.fig.patch.set_facecolor('white')
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self)
self.canvas.setFocusPolicy(Qt.StrongFocus)
self.canvas.setFocus()
self.canvas.setMinimumHeight(100)
self.canvas.setMinimumWidth(100)
self.mpl_toolbar = NavigationToolbar2(self.canvas, self)
self.mpl_toolbar.hide()
self.mpl_toolbar.pan()
self.canvas.mpl_connect('scroll_event', self.zooming)
ins = "Left-click+drag to pan x-axis / Right-click+drag to zoom x-axis / Scroll-wheel to change intensity scale"
self.instructionLabel = QLabel(ins)
self.instructionLabel.setStyleSheet('QLabel{qproperty-alignment: AlignCenter; font-size: 10px;}')
self.showignoredregionsCheckBox = QCheckBox("Show Ignored Regions")
self.showignoredregionsCheckBox.setToolTip("Shows the ranges set by the solvent/buffer ignore regions, if any.")
self.showignoredregionsCheckBox.setLayoutDirection(Qt.RightToLeft)
self.showignoredregionsCheckBox.setChecked(True)
self.showignoredpeaksCheckBox = QCheckBox("Show Ignored Peaks")
self.showignoredpeaksCheckBox.setToolTip("Shows any compound peaks that are in the solvent/buffer ignore regions, if any.\n"
"These peaks are ignored and are not evaluated during mixing.")
self.showignoredpeaksCheckBox.setLayoutDirection(Qt.RightToLeft)
self.showignoredpeaksCheckBox.setChecked(True)
self.resetviewButton = QPushButton("Reset View")
self.resetviewButton.setToolTip("Resets the spectrum to the default view.")
self.savespectrumButton = QPushButton("Save Spectrum")
self.savespectrumButton.setToolTip("Saves the image in the spectrum window.")
def initPeaklistTable(self):
# Compound Peaklist Tab
self.compoundtab3 = QWidget()
self.compoundtab3.setStyleSheet("QWidget{background-color: white;}")
self.peakTable = QTableWidget(0, 4, self)
# self.peakTable.setMinimumWidth(400)
self.peakTable.setSelectionMode(QAbstractItemView.NoSelection)
self.peakTable.setSelectionBehavior(QAbstractItemView.SelectRows)
self.peakTable.setSelectionMode(QAbstractItemView.SingleSelection)
self.peakTable.setSortingEnabled(True)
self.peakTable.sortByColumn(1, Qt.AscendingOrder)
self.peakTable.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.peakTable.setColumnWidth(0, 100)
self.peakTable.setColumnWidth(1, 200)
self.peakTable.setColumnWidth(2, 150)
示例12: VelPlotWidget
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import mpl_connect [as 别名]
class VelPlotWidget(QWidget):
""" Widget for a velocity plot with interaction.
Akin to XIDL/x_velplot
19-Dec-2014 by JXP
"""
def __init__(self, ispec, z, abs_lines=None, parent=None, llist=None, norm=True,
vmnx=[-300., 300.]*u.km/u.s):
'''
spec : XSpectrum1D
z : float
abs_lines: list, optional
List of AbsLines
llist : LineList, optional
Input line list. Defaults to 'Strong'
norm : bool, optional
Normalized spectrum?
vmnx : Quantity array, optional
Starting velocity range for the widget
'''
super(VelPlotWidget, self).__init__(parent)
self.help_message = """
Click on any white region within the velocity plots
for the following keystroke commands to work:
i,o : zoom in/out x limits
I,O : zoom in/out x limits (larger re-scale)
y : zoom out y limits
t,b : set y top/bottom limit
l,r : set left/right x limit
[,] : pan left/right
C,c : add/remove column
K,k : add/remove row
=,- : move to next/previous page
1,2 : Modify velocity region of the single line (left, right sides)
!,@ : Modify velocity region of all lines (left, right)
A,x : Add/remove select line from analysis list
X : Remove all lines from analysis list
^,& : Flag line to be analyzed for low/high-ion kinematics
B : Toggle as blend/no-blend (orange color = blend)
N : Toggle as do/do-not include for analysis (red color = exclude)
V : Indicate as a normal value
L : Indicate as a lower limit
U : Indicate as a upper limit
? : Print this
"""
# Initialize
spec, spec_fil = ltgu.read_spec(ispec)
self.spec = spec
self.spec_fil = spec_fil
self.z = z
self.vmnx = vmnx
self.norm = norm
# Abs Lines
if abs_lines is None:
self.abs_lines = []
else:
self.abs_lines = abs_lines
#QtCore.pyqtRemoveInputHook()
#xdb.set_trace()
#QtCore.pyqtRestoreInputHook()
self.psdict = {} # Dict for spectra plotting
self.psdict['x_minmax'] = self.vmnx.value # Too much pain to use units with this
self.psdict['y_minmax'] = [-0.1, 1.1]
self.psdict['nav'] = ltgu.navigate(0,0,init=True)
# Line List
if llist is None:
self.llist = ltgu.set_llist('Strong')
else:
self.llist = llist
self.llist['z'] = self.z
# Indexing for line plotting
self.idx_line = 0
self.init_lines()
# Create the mpl Figure and FigCanvas objects.
self.dpi = 150
self.fig = Figure((8.0, 4.0), dpi=self.dpi)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self)
self.canvas.setFocusPolicy( QtCore.Qt.ClickFocus )
self.canvas.setFocus()
self.canvas.mpl_connect('key_press_event', self.on_key)
self.canvas.mpl_connect('button_press_event', self.on_click)
# Sub_plots (Initial)
self.sub_xy = [3,4]
self.fig.subplots_adjust(hspace=0.0, wspace=0.1)
# Layout
vbox = QVBoxLayout()
vbox.addWidget(self.canvas)
#.........这里部分代码省略.........
示例13: Calibrlogger
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import mpl_connect [as 别名]
#.........这里部分代码省略.........
#self.mpltoolbar.home()
last_calibration = self.getlastcalibration(self.obsid)
try:
if last_calibration[0][1] and last_calibration[0][0]:
self.LoggerPos.setText(str(last_calibration[0][1]))
self.FromDateTime.setDateTime(datestring_to_date(last_calibration[0][0]))
else:
self.LoggerPos.setText('')
self.FromDateTime.setDateTime(datestring_to_date('2099-12-31 23:59:59'))
except Exception as e:
utils.MessagebarAndLog.info(log_msg=ru(QCoreApplication.translate('Calibrlogger', 'Getting last calibration failed for obsid %s, msg: %s'))%(self.obsid, str(e)))
self.LoggerPos.setText('')
self.FromDateTime.setDateTime(datestring_to_date('2099-12-31 23:59:59'))
@fn_timer
def reset_cid(self):
""" Resets self.cid to an empty list and disconnects unused events """
for x in self.cid:
self.canvas.mpl_disconnect(x)
self.cid = []
@fn_timer
def catch_old_level(self):
"""Part of adjustment method 3. adjust level_masl by clicking in plot.
this part selects a line node and a y-position on the plot"""
#Run init to make sure self.meas_ts and self.head_ts is updated for the current obsid.
self.load_obsid_and_init()
self.deactivate_pan_zoom()
self.canvas.setFocusPolicy(Qt.ClickFocus)
self.canvas.setFocus()
self.calib_help.setText(ru(QCoreApplication.translate('Calibrlogger', "Select a logger node.")))
self.cid.append(self.canvas.mpl_connect('pick_event', self.set_log_pos_from_node_date_click))
@fn_timer
def catch_new_level(self):
""" Part of adjustment method 3. adjust level_masl by clicking in plot.
this part selects a y-position from the plot (normally user would select a manual measurement)."""
if self.log_pos is not None:
self.calib_help.setText(ru(QCoreApplication.translate('Calibrlogger', "Select a y position to move to.")))
self.cid.append(self.canvas.mpl_connect('button_press_event', self.set_y_pos_from_y_click))
self.calib_help.setText("")
else:
self.calib_help.setText(ru(QCoreApplication.translate('Calibrlogger', "Something wrong, click \"Current\" and try again.")))
@fn_timer
def calculate_offset(self):
""" Part of adjustment method 3. adjust level_masl by clicking in plot.
this method extracts the head from head_ts with the same date as the line node.
4. Calculating y-position - head (or level_masl) and setting self.LoggerPos.
5. Run calibration.
"""
if self.log_pos is not None and self.y_pos is not None:
utils.start_waiting_cursor()
logger_ts = self.level_masl_ts
y_pos = self.y_pos
log_pos = self.log_pos
self.y_pos = None
self.log_pos = None
log_pos_date = datestring_to_date(log_pos).replace(tzinfo=None)
logger_value = None
#Get the value for the selected node
示例14: ExamineSpecWidget
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import mpl_connect [as 别名]
class ExamineSpecWidget(QWidget):
""" Widget to plot a spectrum and interactively
fiddle about. Akin to XIDL/x_specplot.pro
12-Dec-2014 by JXP
"""
def __init__(self, ispec, parent=None, status=None, llist=None,
abs_sys=None, norm=True, second_file=None, zsys=None,
key_events=True, vlines=None, plotzero=False, exten=None,
xlim=None, ylim=None, rsp_kwargs=None, air=False):
"""
Parameters
----------
ispec : XSpectrum1D, tuple of arrays or filename
exten : int, optional
extension for the spectrum in multi-extension FITS file
parent : Widget parent, optional
status : Point to status bar, optional
llist : dict, optional
Used to guide the line lists
abs_sys : list, optional
AbsSystem's
zsys : float, optional
intial redshift
key_events : bool, optional
Use key events? [True]
Useful when coupling to other widgets
xlim : tuple of two floats
Initial x plotting limits
ylim : tuple of two floats
Initial y plotting limits
air : bool, optional
Spectrum is wavelength calibrated `in air`
"""
super(ExamineSpecWidget, self).__init__(parent)
# Spectrum
spec, spec_fil = ltgu.read_spec(ispec, exten=exten, norm=norm,
rsp_kwargs=rsp_kwargs)
if air:
spec.meta['airvac'] = 'air'
spec.airtovac()
self.orig_spec = spec # For smoothing
self.spec = self.orig_spec
self.parent = parent
# determine the filename (if any)
if isinstance(ispec, (str, basestring)):
filename = ispec
else:
filename = None
self.vlines = []
if vlines is not None:
self.vlines.extend(vlines)
self.plotzero = plotzero
# Other bits (modified by other widgets)
self.model = None
self.bad_model = None # Discrepant pixels in model
self.use_event = 1
# Abs Systems
if abs_sys is None:
self.abs_sys = []
else:
self.abs_sys = abs_sys
self.norm = norm
self.psdict = {} # Dict for spectra plotting
self.adict = {} # Dict for analysis
self.init_spec(xlim=xlim, ylim=ylim)
self.xval = None # Used with velplt
# Status Bar?
if not status is None:
self.statusBar = status
# Line List?
if llist is None:
self.llist = {'Plot': False, 'List': 'None', 'z': 0., 'Lists': []}
else:
self.llist = llist
# zsys
if zsys is not None:
self.llist['z'] = zsys
# Create the mpl Figure and FigCanvas objects.
# 5x4 inches, 100 dots-per-inch
#
self.dpi = 150 # 150
self.fig = Figure((8.0, 4.0), dpi=self.dpi)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self)
self.canvas.setFocusPolicy( QtCore.Qt.ClickFocus )
self.canvas.setFocus()
if key_events:
self.canvas.mpl_connect('key_press_event', self.on_key)
#.........这里部分代码省略.........
示例15: CoqTextgridView
# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import mpl_connect [as 别名]
class CoqTextgridView(QtWidgets.QWidget):
def __init__(self, *args, **kwargs):
super(CoqTextgridView, self).__init__(*args, **kwargs)
self._dynamic_range = 50
self._window_length = 0.005
self._textgrid = None
self._sound = None
self._spectrogram = None
self._drag = False
self._start_pos = None
self.scrollbar = QtWidgets.QScrollBar(QtCore.Qt.Horizontal)
self.scrollbar.valueChanged.connect(self.change_position)
self.figure = CoqFigure()
self.canvas = FigureCanvas(self.figure)
self.canvas.setParent(self)
self.canvas.mpl_connect('key_press_event', self.on_key_press)
self.canvas.mpl_connect('button_release_event', self.on_button_release)
self.canvas.mpl_connect('button_press_event', self.on_button_press)
self.canvas.mpl_connect('motion_notify_event', self.on_mouse_move)
#self.toolbar = NavigationToolbar(self.canvas, self)
#self.toolbar.press_zoom = types.MethodType(press_zoom, self.toolbar)
self.canvas.setSizePolicy(QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Expanding)
self.canvas.updateGeometry()
gs = mpl.gridspec.GridSpec(3, 1, height_ratios=[2.5, 5, 2.5])
self.ax_waveform = self.figure.add_subplot(gs[0],
projection="LockedAxes")
self.ax_spectrogram = self.figure.add_subplot(gs[1],
sharex=self.ax_waveform,
projection="LockedAxes")
self.ax_textgrid = self.figure.add_subplot(gs[2],
sharex=self.ax_waveform,
projection="LockedAxes")
self.figure.subplots_adjust(hspace=0)
# prepare axes
self.ax_waveform.set_ylim([-1, 1])
self.ax_waveform.set_ylabel("Amplitude")
self.ax_waveform.get_xaxis().set_visible(False)
self.ax_spectrogram.set_ylabel("Frequency (Hz)")
self.ax_spectrogram.get_xaxis().set_visible(False)
self.ax_textgrid.set_xlabel("Time (s)")
self.ax_textgrid.xaxis.get_offset_text().set_visible(False)
self.selector_waveform = SpanSelector(
self.ax_waveform, self.on_select, 'horizontal', useblit=True,
rectprops=dict(alpha=0.25, facecolor='red'), span_stays=False,
button=1)
self.selector_spectrogram = SpanSelector(
self.ax_spectrogram, self.on_select, 'horizontal', useblit=True,
rectprops=dict(alpha=0.25, facecolor='red'), span_stays=False,
button=1)
layout = QtWidgets.QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
self.setLayout(layout)
#self.layout().addWidget(self.toolbar)
self.layout().addWidget(self.canvas)
self.layout().addWidget(self.scrollbar)
def clear(self):
#self.layout().removeWidget(self.toolbar)
self.layout().removeWidget(self.canvas)
#del self.toolbar
del self.canvas
del self.figure
def on_key_press(self, *args, **kwargs):
pass
def on_button_press(self, event):
print(event)
if event.button == 1:
if event.inaxes == self.ax_textgrid:
print("clicked", event.xdata)
tier = self._textgrid.get_tier_by_name(
self._textgrid.get_tier_names()[0])
print(tier.intervals)
print("nearest", tier.get_annotations_by_time(event.xdata))
interval = tier.get_annotations_by_time(event.xdata)[0]
self._sound.extract_sound(interval.start_time,
interval.end_time).play()
elif event.button == 3:
QtCore.QCoreApplication.instance().setOverrideCursor(
QtGui.QCursor(QtCore.Qt. SizeHorCursor))
self._drag = True
self._start_pos = event.xdata
def on_mouse_move(self, event):
if not event.button:
return
if self._drag and event.xdata:
dist = self._start_pos - event.xdata
trans = self.ax_textgrid.transAxes.transform([dist, 0])[0]
#.........这里部分代码省略.........