问题
matplotlib pyplot has a function called waitforbuttonpress() which will return either True or False depending on whether a keyboard or mouse event is received within a graph.
As such mouse events are returned by waitforbuttonpress() even if the user interact with the figure using normal graph tools (such as zooming), the only way to use this function is as follows: (assuming the zooming function should be available)
while not plt.waitforbuttonpress(): pass #ignore mouse events use by zomming ...
The above will block untill a keyboard key is pressed (as opposed to mouse event which will be handled normally,e.g. for zooming)
Is there a way to know which key was pressed, to distinguish between different choices?
回答1:
I don't think that's directly possible, but you can get the key value from a key_press_event, which will be fired at the same time as waitforbuttonpress():
import matplotlib.pyplot as plt
the_key = None
def press(event):
global the_key
the_key = event.key
plt.figure()
plt.plot([1, 4, 6])
plt.gcf().canvas.mpl_connect('key_press_event', press)
while not plt.waitforbuttonpress(): pass # ignore mouse events use by zomming ...
print("You pressed: ", the_key)
来源:https://stackoverflow.com/questions/56669721/get-the-key-value-when-calling-matplolib-pyplot-waitforbuttonpress