简体   繁体   English

暂停python并等待Matplotlib事件

[英]Pause python and wait for Matplotlib event

I want to pause my python script while I wait for a user to press enter - while the focus is on a matplotlib figure. 我想在等待用户按Enter时暂停python脚本-而焦点在matplotlib图上。

I tried the following code, but the script binds up the the event handling when it goes into the wile loop. 我尝试了以下代码,但是当脚本进入wile循环时,该脚本将事件处理绑定了起来。 Making it so the user is unable to draw the rectangle. 使得用户无法绘制矩形。

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
    '''

Pausing the program with something like 用类似的方法暂停程序

print "press enter to continue:"
raw_input()

Does work, but requires the user to return focus to the terminal screen, then press enter. 可以,但是需要用户将焦点返回到终端屏幕,然后按Enter。

Any recommendations on how to pause the script until an event is registered in matplotlib? 关于如何暂停脚本,直到在matplotlib中注册了事件的任何建议?

I think you'll have to implement a simple (single window) GUI and include a matplotlib graphical backend inside that. 我认为您必须实现一个简单的(单个窗口)GUI,并在其中包含一个matplotlib图形后端。

You might be in luck: the matplotlib examples provide a nice example. 您可能很幸运: matplotlib示例提供了一个很好的示例。 Note how, when running the example, keypresses are caught and printed to the terminal, but also forwarded to matplotlib.backend_bases.key_press_handler . 请注意,在运行示例时,如何捕获按键并打印到终端,又如何将其转发到matplotlib.backend_bases.key_press_handler

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM