如何弹出图并等待响应

问题描述

我正在写一个python循环,其中弹出了一个数字,我保存了坐标,然后进行了一些计算。我的问题是: 1-如何停止循环,直到按下鼠标并存储坐标? 2-如何将坐标存储在变量中而不是打印? 3-如何用同一事件关闭人物?

import matplotlib.pyplot as plt
import numpy as np


fig,ax = plt.subplots()
fig.canvas.callbacks.connect('button_press_event',callback)

def callback(event):
    return event.xdata,event.ydata
    

for i in range(3):
    
    print('before')
    ax.plot(np.arange(1,11,1),np.arange(50,60,1))
    
    # how to wait for mouse click
    # How to save in variable
    coordinates = get event.xdata,event.ydata  #??
    
    "then proceed the loop"
    # do any calculations using event.xdata,event.ydata
    

解决方法

由于您只说了一个循环,并且想要一个可笑的人物。实际上,图形弹出并不是您必须使用的。您可以使用两个子图,一个用于绘制原始数据,另一个用于显示新的“弹出”图形。但是您必须在python类中编写它。这是一些演示代码供您使用:

import numpy as np
import matplotlib.pyplot as plt

class Demo:
    
    def __init__(self,fig,x,y):
        self.fig = fig
        self.ax1 = fig.axes[0]
        self.ax2 = fig.axes[1]
        self.x = x
        self.y = y
        
        self.ax1.plot(x,y)
        
        self.click = self.fig.canvas.mpl_connect("button_press_event",self.onclick)
        
    def onclick(self,event):
        x,y = event.xdata,event.ydata
        print(x,y)
        # do calculation here,plot another figure here
        # get the distance to point (x,y)
        d = np.sqrt((self.x-x)**2+(self.y-y)**2)
        # plot d in second ax
        if len(self.ax2.lines) != 0:
            self.ax2.lines = []
            self.ax2.plot(d)
        else:
            self.ax2.plot(d)
        self.fig.canvas.draw_idle()
        
        
x = np.linspace(-4,4,256)
y = np.sin(x)
fig,(ax1,ax2) = plt.subplots(1,2,figsize=(7.2,7.2/2))
app = Demo(fig,y)

尝试单击左侧的斧头,看看右侧的斧头是如何变化的。享受吧!