How can I detect double click events in matplotlib?
import matplotlib.pyplot as plt
def onclick(e开发者_开发技巧vent):
print event.button
fig = plt.figure()
connection_id = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
With a construct like this, I have the problem of double-clicks hitting onclick()
handler three times. I guess that it is receiving both the clicks, and an additional double-click event. How can I change this behaviour so that the event handler is not fired for double-click events? Or, alternatively, how can I detect them from the event instance so that I can ignore those double-clicks?
note: button_release_event
does not have this problem, but I want to fire on the button_press_event
When i had matplotlib version 1.1rc, i was not able to catch dblclick event. Later, I wrote code for matplotlib 1.2 and that is ok
import matplotlib.pyplot as plt
fig = plt.figure()
def onclick(event):
if event.dblclick:
print event.button
connection_id = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
I was able to detect the case by using
from gtk.gdk import BUTTON_PRESS, _2BUTTON_PRESS. _3BUTTON_PRESS
note: the reason for underscores on double and triple click enum types is not that they are _protected, but to dodge the issue where you aren't allowed to have an attribute starting with a number. You can check the event type with:
event.guiEvent.type
However, I later found out that the import will cause an exception if you are using a different backend (moreover, I only have this problem with 'GTKAgg' backend). So now I use a construct like this:
from gtk.gdk import BUTTON_PRESS as singleclick
if plt.get_backend() == 'GTKAgg':
if hasattr(event, 'guiEvent') and event.guiEvent.type != singleclick:
# suppress double click event
return
If anyone has a cleaner solution, feel free to add it here.
I had encountered the same problem when I was using matplotlib 1.1. There was no 'dblclick' event type. So I implemented it by myself. I required the time interval between two clicks must be smaller than 0.5 sec or the program would do nothing. User could tune this setting by itself according to its experience.
import matplotlib.pyplot as plt
import time
fig = plt.figure()
one_click_trigger = False
time_first_click = 0
def mouseDoubleClick(event):
global one_click_trigger
global time_first_click
if one_click_trigger == False:
one_click_trigger = True
time_first_click = time.time()
return
else:
double_click_interval = time.time() - time_first_click
if double_click_interval > 0.5:
one_click_trigger = False
time_first_click = 0
return
print "Double click!"
fig.canvas.mpl_connect('button_press_event', mouseDoubleClick)
plt.show()
精彩评论