简体   繁体   English

在matplotlib中的button_press_event期间暂停执行

[英]Pause execution during button_press_event in matplotlib

I am trying to plot a polygon of user clicks and render them over a matplotlib canvas: 我试图绘制用户点击的多边形并在matplotlib画布上渲染它们:

def helperClick(self, clickEvent):
        self.lastXClick = clickEvent.x 
        self.lastYClick = clickEvent.y
        self.lastButtonClick = clickEvent.button

def measurePoly(self):

    self.lastButtonClick = None
    cid = self.ui.canvas2.mpl_connect('button_press_event', self.helperClick)

    #Exit render loop on right click
    while self.lastButtonClick != 3:
       print('waiting')
       if self.lastButtonClick == 1:
           #Eventually render polygon on click of 1
           print('clicked')

    self.ui.canvas2.mpl_disconnect(cid)

    #do more stuff with polygon data

I am just trying to "wait" for user clicks, do something on a user click, then continue down the function on a left-click. 我只是试图“等待”用户点击,在用户点击上执行某些操作,然后通过左键单击继续执行该功能。 However, my infinite loop freezes up python and crashes. 然而,我的无限循环冻结了python和崩溃。 I know this is a bad way to do this (clearly as it doesn't work :P) but I am not sure how to properly do this. 我知道这是一个不好的方法(显然它不起作用:P)但我不知道如何正确地做到这一点。

Thanks, 谢谢,

tylerthemiler tylerthemiler

It sounds like you're trying to manually run the "mainloop" in your own code? 听起来你正试图在自己的代码中手动运行“mainloop”?

The whole point of using callback functions is that you let the gui toolkit run its own mainloop (in this case, it's entered when you call show ). 使用回调函数的关键在于让gui工具包运行自己的mainloop(在这种情况下,当你调用show时它会被输入)。

Here's a very simple example of something along the lines of what you're trying to do. 这是一个非常简单的例子,说明你正在尝试做的事情。

It adds verticies when you left-click on the (initially blank) plot, and then draws the corresponding polygon when you right click. 当您左键单击(最初为空白)绘图时,它会添加顶点,然后在右键单击时绘制相应的多边形。 Nothing is drawn until you right-click (It's not too hard to draw the polygon while you're adding points by left-clicking, but doing it efficiently in matplotlib is a bit verbose). 在右键单击之前不会绘制任何内容(在通过左键单击添加点时绘制多边形并不太难,但在matplotlib中有效地执行它有点冗长)。

import matplotlib.pyplot as plt

class Plot(object):
    def __init__(self):
        self.poly = []
        self.fig, self.ax = plt.subplots()
        self.ax.axis([0, 10, 0, 10])
        self.fig.canvas.mpl_connect('button_press_event', self.on_click)

        plt.show()

    def on_click(self, event):
        if event.button == 1:
            self.poly.append((event.xdata, event.ydata))
        elif event.button == 3:
            self.draw_poly()

    def draw_poly(self):
        self.ax.fill(*zip(*self.poly))
        self.poly = []
        self.fig.canvas.draw()

Plot()

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

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