I'm practicing tkinter and matplotlib in this piece of code and what it is supposed to do is to embed a simple matplotlib graph into a tkinter GUI. The thing is I also want horizontal lines to be plotted in this embedded graph by mouse clicks but I'm not getting the result I want.
What I'm getting is that by the first mouse click a new plot is created outside the tkinter GUI of the same graph with one horizontal line in it (where it was clicked on). If I close this plot window that popped up and try to click again on the embedded graph a new plot pops up but this time it contains only a horizontal line.
What's going on?
The code I'm practicing on:
from tkinter import * import matplotlib matplotlib.use('TkAgg') from matplotlib import pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib.figure import Figure root = Tk() frame = Frame(root) frame.pack() fig = plt.figure(figsize=(16,8)) plt.plot([1,2,3],[1,2,3]) canvas = FigureCanvasTkAgg(fig, frame) canvas.show() canvas.get_tk_widget().pack(fill='both', expand=True) toolbar = NavigationToolbar2TkAgg(canvas, frame) toolbar.update() canvas._tkcanvas.pack(fill='both', expand=True) def pick(event): plt.ion() plt.hlines(event.ydata,event.xdata-0.009,event.xdata+0.009,colors='red', linestyle='solid') fig.canvas.mpl_connect('button_press_event', pick)