【发布时间】:2020-04-28 05:29:52
【问题描述】:
我正在使用 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.xdata和event.inaxes等方法来避免不必要的额外工作。
谢谢。
【问题讨论】:
标签: python matplotlib tkinter click wait