get the key value when calling matplolib pyplot waitforbuttonpress()

杀马特。学长 韩版系。学妹 提交于 2021-01-29 03:52:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!