如何将CTRL+scroll绑定到matplotlib图形?

2024-05-08 09:33:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将matplotlib图形中的CTRL+scroll绑定到缩放功能。我知道在matplotlib中,我可以使用fig.canvas.mpl_connect('key_press_event', buttonpressed)将某个按钮绑定到函数(buttonpressed),使用fig.canvas.mpl_connect('scroll_event', scrollused)将滚动绑定到函数(scrollused),但将这两者结合起来的最佳方法是什么

是否有可能将两者结合到一个函数调用中?还是我必须求助于解决这个问题?例如,在按下CTRL键时将变量设置为true,在再次释放时将变量设置为false,并在scroll函数调用中检查此变量

可以在here.中找到绑定

具有CTRL-bind和scroll-bind(但不组合)的图形的最小工作示例:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.plot(np.random.rand(10))

def scrolled(event):
    print('scroll used')

def ctrlpressed(event):
    if event.key == 'control':
        print('CTRL pressed')

# Bind to figure
fig.canvas.mpl_connect('key_press_event', ctrlpressed)
fig.canvas.mpl_connect('scroll_event', scrolled)
fig.show()

Tags: key函数event图形matplotlibconnectfigmpl
1条回答
网友
1楼 · 发布于 2024-05-08 09:33:24

到目前为止,我找到的最佳解决方案是将ctrl键按下、ctrl键释放和滚动键分开绑定。按下控制键可将检查变量设置为true,按下ctrl键可再次将其设置为false。滚动条检查此变量。在这种情况下,结果对于用户来说就像是ctrl+滚动

请参阅本文中给出的示例代码(globals是此MWE的一个变通方法。在我自己的代码中,我使用的是面向对象的方法):

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.plot(np.random.rand(10))

ctrl = False

def scrolled(event):
    global ctrl
    if ctrl:
        print('ctrl+scroll used')

def ctrlpressed(event):
    global ctrl
    if event.key == 'control':
        ctrl = True

def ctrlreleased(event):
    global ctrl
    if event.key == 'control':
        ctrl = False
        

# Bind to figure
fig.canvas.mpl_connect('key_press_event', ctrlpressed)
fig.canvas.mpl_connect('key_release_event', ctrlreleased)
fig.canvas.mpl_connect('scroll_event', scrolled)
fig.show()

相关问题 更多 >