从Tkinter画布检索坐标

2024-04-23 07:18:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我绘制了一组点,并将其嵌入到Tkinter画布中。我要做的是在单击一个/多个点时检索坐标。我可以使用下面的代码(在嵌入到Tkinter之前)。但是,它只适用于迭代中的第一个绘图。接下来的两个情节我该如何扩展?有人能解释一下需要用画布做的改变吗?在

outl=[]
index = []
list_rep = []
def on_pick(event):
        thisline = event.artist
        xdata, ydata = thisline.get_data()
        tmp = []

        index.append(i)
        ind = event.ind
        tmp.append(list(xdata[ind])[0])
        tmp.append(list(ydata[ind])[0])
        outl.append(tmp)


        #print('on pick line:', zip(xdata[ind], ydata[ind]))

new_ydata1 = []
new_ydata2 = []
new_ydata3 = []
for i in range(3):
        root = Tk.Tk()
        root.wm_title("Embed in Tk")

        ydata1 = np.array(Max_Correct_1[i])
        ydata2 = np.array(Max_Correct_2[i])
        ydata3 = np.array(Max_Correct_3[i])

        Aveg=np.array(Avg[i])


        f = Figure(figsize=(5,4), dpi=100)
        ax1 = f.add_subplot(111)

        ax1.axis([-9.5,-4.0,-10,105])
        ax1.plot(Log_Values_Array,ydata1,'o',picker=7)
        ax1.plot(Log_Values_Array,ydata2,'*',picker=7)
        ax1.plot(Log_Values_Array,ydata3,'^',picker=7)
        ax1.plot(Log_Values_Array,Aveg,'b--')

        canvas = FigureCanvasTkAgg(f, master=root)

        canvas.show()
        canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)


        canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

        canvas.mpl_connect('pick_event',on_pick)




        print outl



        canvas.get_tk_widget().delete("all")
        outl=[]
        index = []
        Tk.mainloop()

Tags: eventlogplotnparraytmptkcanvas
1条回答
网友
1楼 · 发布于 2024-04-23 07:18:27

我相信这与您试图通过使用循环来创建Tk的多个实例有关,并尝试对每个实例调用mainloop。对于一个给定的应用程序,应该只有一个Tk,因此只对该实例调用mainloop。在

在进入for循环之前,创建根Tk实例。进入循环后,使用TopLevel小部件将每个绘图窗口创建为该根的子窗口。循环结束后,在根上调用mainloop。在

下面是一个非常的大致代码大纲,应该可以使用:

# Code before loop just as it is, except you create your root Tk instance here...
root = Tk.Tk()

# Now start the loop
for i in range(3):
    win = Tk.TopLevel(root)
    win.title(text="Embed in Tk")
    ...
    # The rest of your plot-building code goes here, with all new widgets
    # as children of the window "win"

# Now that the loop is finished, call mainloop
root.mainloop()

如果不能访问您的数据(以及您正在使用的其他模块),很难确认这是否能满足您的需要,但它应该能做到这一点。在

为了更有效地工作,您可能需要考虑为每个绘图窗口构建一个类(子类化TopLevel),然后使用循环创建三个实例,将适当的数据传递给每个实例。这样每个绘图窗口和操作都可以被隔离。在

相关问题 更多 >