Matplotlib按钮 [英] Matplotlib Button
问题描述
Matplotlib窗口小部件按钮事件和fig.canvas.mpl_connect('button_press_event')都将在单击鼠标按钮时被触发.
Matplotlib Widget Buttons event and fig.canvas.mpl_connect('button_press_event') will both be triggered when mouse is clicked against the button.
我的问题是:
1)如何使fig.canvas.mpl_connect('button_press_event')事件具有更高的优先级?和2)如何在fig.canvas.mpl_connect('button_press_event')事件中判断按钮是否被点击.
1) how to make fig.canvas.mpl_connect('button_press_event') event have a higher priority ? and 2) how to tell within an fig.canvas.mpl_connect('button_press_event') event whether the button is being clicked or not.
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
fig = plt.figure()
# plotting
X=[1,2,3]
Y=[10,20,30]
ax = fig.add_subplot(1, 1, 1)
ax.plot(X,Y,'bo-')
ax.grid()
ax.legend()
X1=[]
Y1=[]
def on_press(event):
print "canvas clicked"
print "how can I tell whether the button is clicked?"
print event
def on_button_clicked(event):
print "button clicked"
print event
axnext = plt.axes([0.81, 0.05, 0.1, 0.075])
bnext = Button(axnext, 'Next')
bnext.on_clicked(on_button_clicked)
fig.canvas.mpl_connect('button_press_event', on_press)
plt.show()
推荐答案
关于第一点,为什么需要它?在这种情况下,您可以忽略事件吗?
About the first point, why do you need that? Can you just ignore the event in that case?
关于第二点,您可以使用 bnext.label.clipbox.get_points()
提取按钮的坐标,并将其与鼠标事件的坐标进行比较,如示例中所示下方:
Regarding the second point, you can use bnext.label.clipbox.get_points()
to extract the coordinates of the button, and compare them with the coordinates of the mouse event, like in the example below:
import matplotlib.pylab as plt
from matplotlib.widgets import Button
fig,ax = plt.subplots()
ax.plot([1,2,3],[10,20,30],'bo-')
axnext = plt.axes([0.81, 0.05, 0.1, 0.075])
bnext = Button(axnext, 'Next')
(xm,ym),(xM,yM)=bnext.label.clipbox.get_points()
def on_press(event):
if xm<event.x<xM and ym<event.y<yM:
print "Button clicked, do nothing. This triggered event is useless."
else:
print "canvas clicked and Button not clicked. Do something with the canvas."
print event
def on_button_clicked(event):
print "button clicked, do something triggered by the button."
print event
bnext.on_clicked(on_button_clicked)
fig.canvas.mpl_connect('button_press_event', on_press)
plt.show()
这篇关于Matplotlib按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!