0

I have created a set of plots with matplotlib embedded in a GUI using tkinter, but I would like to make this "figure" scrollable so that the plots can fill a larger space. The scrollbar would allow for different plots to be viewed by scrolling in the vertical direction. So far I have tried the following

from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg, NavigationToolbar2Tk)
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import tkinter as tk
from tkinter import ttk

x=[0,1,2,3,4,5]
y=[0,2,4,8,16,32]

window = tk.Tk()
window.geometry('1600x880')
tab_collection = ttk.Notebook(window)
first_tab = ttk.Frame(tab_collection)
tab_collection.add(first_tab, text='First Tab')
tab_collection.pack(expand=1, fill='both')

first_tab_left=tk.Frame(first_tab)
first_tab_left.pack(side=tk.LEFT)
first_tab_right=tk.Frame(first_tab)
first_tab_right.pack(side=tk.RIGHT)

my_fig = plt.Figure(figsize=(13,10))

my_canvas = FigureCanvasTkAgg(my_fig, first_tab_right)
my_canvas.get_tk_widget().pack(padx=20,side=tk.BOTTOM, fill=tk.BOTH, expand=False)
toolbar = NavigationToolbar2Tk(my_canvas, first_tab_right)
toolbar.update()
my_canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=False)

#scrollbar for plots
scrollbar = tk.Scrollbar(master = first_tab_right, orient= tk.VERTICAL)
scrollbar.pack(side= tk.RIGHT, fill= tk.Y)

scrollbar["command"] = my_canvas.get_tk_widget().yview
my_canvas.get_tk_widget()["yscrollcommand"] = scrollbar.set

#plot data and draw canvas
my_ax= my_fig.add_subplot(2,1,1)
my_ax.plot(x,y)
my_ax= my_fig.add_subplot(2,1,2)
my_ax.plot(x,y)

my_fig.tight_layout()
my_canvas.draw()

window.mainloop()

The scrollbar is not appearing with this code and I cannot scroll downwards. Is subplots the wrong way to go?

I tried to minimalise the code as much as possible. Let me know if it needs more explanation.

Thanks for your help!

gabri
  • 62
  • 8

1 Answers1

0

I can't seem to find a way to attach a scrollbar to the TkAgg canvas created through the matplotlib library. I guess it must be a different kind of canvas. The only answer I have been able to come up with follows this similar question. Basically you have to create a new canvas and add a scrollbar to it. The link has a thoroughly explained answer with easily understandable code so I won't add code to this answer, but what I did was create a new canvas and embed my frame (with the matplotlib canvas) to that canvas to which I can attach a scrollbar.

gabri
  • 62
  • 8