暂停Python并等待Matplotlib事件

2 投票
1 回答
1618 浏览
提问于 2025-04-17 20:43

我想在我的Python脚本中暂停,等用户按下回车键,同时保持matplotlib图形的焦点。

我试过以下代码,但当进入循环时,脚本会阻塞事件处理,这样用户就无法绘制矩形了。

class DrawRectangle:

    def __init__(self, image):
        self.waiting_for_entry = True
        '''
        Event handling that lets user draw a rectangle on an image. 
        when the user is done drawing they press "enter" to disconnect the canvas
        '''

    def on_key_press(self, event):
        if event.key == 'enter':
            '''
            disconnect event handling
            '''
            self.waiting_for_entry = False

    def return_image_inside(self):
        '''
        Return the portion of the image inclosed in the rectangle
        '''

if __name__ == "__main__":
    image = import_some_image() # import an image
    image_plot = plt.imshow(image)
    selector = DrawRectangle(image_plot)

    while selector.waiting_for_entry:
        pass

    working_data = selector.return_image_inside()

    '''
    do stuff with selected image
    '''

用类似这样的方式暂停程序

print "press enter to continue:"
raw_input()

是可行的,但需要用户先把焦点切回终端屏幕,然后再按回车。

有没有什么建议可以让脚本暂停,直到在matplotlib中注册到一个事件呢?

1 个回答

0

我觉得你需要做一个简单的(单窗口)图形用户界面(GUI),然后在里面加入一个matplotlib的图形后端。

你可能会很幸运,因为matplotlib的示例提供了一个很好的例子。注意,当你运行这个例子时,按键操作会被捕捉并打印到终端,同时也会转发给matplotlib.backend_bases.key_press_handler

撰写回答