在tkk框架中的可拾取matplotlib图

时间:2018-05-30 15:52:42

标签: python matplotlib tkinter

我想有一个GUI,其中界面的一部分包含一个绘图,窗口的其余部分包含一些工具来处理绘图。

我想使用mpl_connect将matplotlib画布与tkk框架连接起来,这样我就可以在绘图中选择要使用的点。

这是我的尝试,懦弱地拒绝做我认为它应该做的事情:

import Tkinter as tk
import ttk

from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg, NavigationToolbar2TkAgg)

import matplotlib.pyplot as plt
import numpy as np 

class Frame_examples_program():
    def __init__(self):
        self.window = tk.Tk()
        self.window.title("Amazing GUI 5000")
        self.create_widgets()


    def create_widgets(self):
        self.window['padx'] = 10
        self.window['pady'] = 10

        # - - - - - - - - - - - - - - - - - - - - -
        # Frame
        frame1 = ttk.Frame(self.window, relief=tk.RIDGE)
        frame1.grid(row=0, column=0, sticky=tk.E + tk.W + tk.N + tk.S, padx=0, pady=0)

        frame2 = ttk.Frame(self.window, relief=tk.RIDGE)
        frame2.grid(row=1, column=0, sticky=tk.E + tk.W + tk.N + tk.S, padx=0, pady=0)        
        self.PlotFrame(frame1, frame2)


    class PlotFrame():
        # The plot
        def __init__(self, parent1, parent2):
            self.parent1 = parent1
            self.parent2 = parent2
            canvas = self.plot()
            self.plot_toolbar(canvas)

        def plot(self):
            # the actual plot
            fig, ax = plt.subplots()
            plt.imshow(np.ones((100,100)),picker=True)
            canvas = FigureCanvasTkAgg(fig, self.parent1)
            canvas.mpl_connect('button_press_event', self.onclick)
            return(canvas)

        def plot_toolbar(self, canvas):
            # the tool bar to the plot
            toolbar = NavigationToolbar2TkAgg(canvas, self.parent2)
            toolbar.update()
            canvas.get_tk_widget().grid(row=1, column=1)
            canvas.draw()

        def onclick(self, event):
            # the devilish thing that does nothing!
            print('WOHOOOO')




# Create the entire GUI program
program = Frame_examples_program()

# Start the GUI event loop
program.window.mainloop()

正如您在运行时所看到的那样,matplotlib工具栏非常适用,但我无法调用onclick事件!为什么呢?

1 个答案:

答案 0 :(得分:2)

通过PlotFrame创建的self.PlotFrame(frame1, frame2)实例不会存储在任何地方,因此会收集垃圾。在您期望回调发生的时刻,此实例不再存在于内存中。

解决方案:确保始终保持对PlotFrame的引用,例如

self.myplot = self.PlotFrame(frame1, frame2)

请注意,这是一个或多或少的一般规则:如果不将其存储在任何地方,您几乎不会实例化类。如果您遇到麻烦并且没有遇到麻烦,那大多数情况下表明根本不需要该课程。