matplotlib 在Tkinter中使用鼠标绘制选择区域

9jyewag0  于 2022-12-04  发布在  其他
关注(0)|答案(2)|浏览(160)

我正在开发一个应用程序,它以.csv的形式从用户那里获取输入,并使用matplotlib为相应的值绘制图形。

def plotgraph():
    x = []
    y = []
    data = text.get("1.0", END)
    sepFile = data.split('\n')

    for plotPair in sepFile:
        xAndY = plotPair.split(',')
        if len(xAndY[0]) != 0 and len(xAndY[1]) != 0:
            x.append(float(xAndY[0]))
            y.append(float(xAndY[1]))

    graph = Figure(figsize=(5,4), dpi=100)
    a = graph.add_subplot(111)
    a.plot(x,y)
    a.set_xlabel('Velocity')
    a.set_ylabel('Absorbance')
    canvas = FigureCanvasTkAgg(graph, master=RightFrame)
    canvas.show()
    canvas.get_tk_widget().grid(column=2, row=1, rowspan=2, sticky=(N, S, E, W))

我想在Tkinter中有一个类似的Matplotlib: draw a selection area in the shape of a rectangle with the mouse函数,在选择后得到x0, x1, y0, y1。我可以让已经问过的问题发挥作用,并根据我的需要自定义它,但不知道我在__init__(self)中犯了什么错误

root = Tk()
class Annotate(object):
    def __init__(self):
        self.fig = mplfig.Figure(figsize=(1.5, 1.5))
        self.ax = self.fig.add_subplot(111)
        self.ax.plot([0,1,2,3,4],[0,8,9,5,3])        
        self.canvas = tkagg.FigureCanvasTkAgg(self.fig, master=root)
        self.x0 = None
        self.y0 = None
        self.x1 = None
        self.y1 = None
        self.ax.figure.canvas.mpl_connect('button_press_event', self.on_press)
        self.ax.figure.canvas.mpl_connect('button_release_event', self.on_release)
        self.ax.figure.canvas.mpl_connect('motion_notify_event', self.on_motion)

当我运行这段代码时,我得到一个空白的Tk窗口。有人能告诉我我应该做什么吗?我做错了什么

wa7juj8i

wa7juj8i1#

要使用类,您需要在列表中列出类似以下内容

class Annotate(object):
    def __init__(self):
        print "Annotate is runing"
        # rest of your code

root = Tk()
my_object = Annotate()

root.mainloop()

而且可能你还需要做更多的工作。

omtl5h9j

omtl5h9j2#

我认为现在最简单的方法是使用NavigationToolbar2Tk matplotlib类,它提供了一个内置的工具栏,带有缩放选择器、滚动条等。
这在“Embedding in Tk”示例中显示,在上面的代码中,它将转换为类似于以下内容的代码:

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk

def plotgraph():
    x = []
    y = []
    data = text.get("1.0", END)
    sepFile = data.split('\n')

    for plotPair in sepFile:
        xAndY = plotPair.split(',')
        if len(xAndY[0]) != 0 and len(xAndY[1]) != 0:
            x.append(float(xAndY[0]))
            y.append(float(xAndY[1]))

    graph = Figure(figsize=(5,4), dpi=100)
    a = graph.add_subplot(111)
    a.plot(x,y)
    a.set_xlabel('Velocity')
    a.set_ylabel('Absorbance')
    canvas = FigureCanvasTkAgg(graph, master=RightFrame)
    canvas.show()
    canvas.get_tk_widget().grid(column=2, row=1, rowspan=2, sticky=(N, S, E, W))

    # set pack_toolbar to False to be able to use grid to set position
    toolbar = NavigationToolbar2Tk(canvas, RightFrame, pack_toolbar=False)
    toolbar.grid(column=2, row=3, stick="nw")
    toolbar.update()

相关问题