首页 > 解决方案 > 如何让 tkinter mainloop 等待 matplotlib 点击事件

问题描述

我正在使用 Tkinter 和 matplotlib 构建一个带有嵌入式绘图的 GUI。我在我的窗口中嵌入了一个图形,现在希望使用 matplotlib 的事件处理程序从图形中获取两组 x,y 坐标,然后使用这些坐标创建一条从图形中的数据中减去的直线。代码的简化版本如下所示:

import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
import tkinter as tk

#ideally this uses matplotlib's event handler and also waits for a click before registering the cooridnates
def choose_points():
    points = []
    window.bind("<Button-1>", on_click)
    points.append(graph_xy)
    window.bind("<Button-1>", on_click)
    points.append(graph_xy)
    return points

def on_click(event):
    window.unbind("<Button-1")
    window.config(cursor="arrow")
    graph_xy[0]=event.x
    graph_xy[1]=event.y

def line(x1=0,y1=0,x2=1,y2=1000):
    m=(y2-y1)/(x2-x1)
    c=y2-m*x2
    line_data=[]
    for val in range(0,20):
        line_data.append(val*m + c)
    return line_data

def build_line():
    points = []
    points = choose_points()
    #store line in line_list
    line_list=line(points[0],points[1],points[2],points[3])

#lists needed
line_list=[]
graph_xy=[0,0]

#GUI
window=tk.Tk()
window.title("IPES Graphing Tool")
window.geometry('1150x840')

#Make a frame for the graph
plot_frame = tk.Frame(window)
plot_frame.pack(side = tk.TOP,padx=5,pady=5)

#Button for making the straight line
line_btn = ttk.Button(plot_frame,text="Build line", command = build_line)
line_btn.grid(row=4, column=2,sticky='w')

#make empty figure
fig1=plt.figure(figsize=(9,7))
ax= fig1.add_axes([0.1,0.1,0.65,0.75])

#embed matplotlib figure
canvas = FigureCanvasTkAgg(fig1, plot_frame)
mpl_canvas=canvas.get_tk_widget()
canvas.get_tk_widget().pack(padx=20,side=tk.BOTTOM, fill=tk.BOTH, expand=False)
toolbar = NavigationToolbar2Tk(canvas, plot_frame)
toolbar.update()
canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=False)

window.mainloop()

显然,这个例子没有以任何方式绘制或使用线,坐标也不正确,因为它们没有转换为图形的坐标。我尝试将其替换为window.bind("<Button-1>",wait_click)plt.connect('button_press_event',on_click)但这不会等待单击,因此由于程序尝试访问points但它是空的,因此会发生错误。

我想使用 matplotlib 事件处理的功能,这样我就可以使用 和 等方法event.xdataevent.inaxes避免不必要的额外工作。

谢谢你。

标签: pythonmatplotlibtkinterclickwait

解决方案


您应该使用canvas.mpl_connect触发您的事件,然后检索xdataydata来绘制线。请参阅下面的示例:

import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
import tkinter as tk

window=tk.Tk()
window.title("IPES Graphing Tool")
window.geometry('1150x840')

plot_frame = tk.Frame(window)
plot_frame.pack(side = tk.TOP,padx=5,pady=5)

fig1=Figure(figsize=(9,7))
ax= fig1.add_axes([0.1,0.1,0.65,0.75])

canvas = FigureCanvasTkAgg(fig1, window)
canvas.get_tk_widget().pack(padx=20,side=tk.TOP, fill=tk.BOTH, expand=False)
toolbar = NavigationToolbar2Tk(canvas, window)
toolbar.update()

class DrawLine: # a simple class to store previous cords
    def __init__(self):
        self.x = None
        self.y = None

    def get_cords(self, event):
        if self.x and self.y:
            ax.plot([self.x, event.xdata], [self.y, event.ydata])
            canvas.draw_idle()
        self.x, self.y = event.xdata, event.ydata

draw = DrawLine()
canvas.mpl_connect('button_press_event', draw.get_cords)

window.mainloop()

推荐阅读