使用matplotlib set_data后,TKinter鼠标button_press_event无效的xdata和ydata

时间:2019-02-15 11:49:28

标签: python matplotlib tkinter

我正在构建一个Python TKinter应用程序,在其中我正在动态更新一些嵌入式Matplotlib图像。这些图像的大小可能会在运行时更改。我希望能够检测这些Matplotlib图像中鼠标单击的位置。不幸的是,event.xdata和event.ydata变量始终在初始范围内,并且不会使用set_data更新为重新缩放的数据集。 可能我必须通知画布或鼠标单击事件,如图所示的数组的大小已更改,但是我该怎么做?

import numpy as np
import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure

class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent

        # Initialize normally
        fig = Figure(figsize=(10, 4))
        ax = fig.add_subplot(111)
        ax.axis('off')
        im = ax.imshow(np.zeros((480, 640), dtype=np.uint8), vmin=0, vmax=255)

        canvas = FigureCanvasTkAgg(fig, master=self.parent)
        canvas.draw()
        canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        canvas.mpl_connect("button_press_event", self.on_mouse_presegmented_click)

        # This part may be in a callback in order top update the content of the 
        im.set_data(np.ones((200, 200), dtype=np.uint8) * 255)
        canvas.draw()

    def on_mouse_presegmented_click(self, event):
        # This is always in the range (480, 640), even though it should later be (200, 200)
        print(int(event.xdata), int(event.ydata))

if __name__ == "__main__":
    root = tk.Tk()
    MainApplication(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

在使用set_data而不是(480,640)之后,我希望event.xdata和event.ydata处于(200,200)范围内。另外,在使用set_data后,画布形状似乎不会更新(应该是正方形)。

0 个答案:

没有答案