Search code examples
python-3.xtkintercanvasframe

python tk tkinter multiple canvas can not afford in my scrollable frame


import tkinter as tk
from tkinter import filedialog
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg,  NavigationToolbar2Tk) 
from matplotlib.figure import Figure 
import matplotlib.pyplot as plt
from data import dataprocess
root = tk.Tk()
root.geometry('1500x800')
container = tk.Frame(root)
main_canvas = tk.Canvas(container, width=1480, height=800,  bg='blue')
scrollbar = tk.Scrollbar(container, orient="vertical", command=main_canvas.yview)
scrollable_frame = tk.Canvas(main_canvas, bg='black')
scrollable_frame.bind(
"<Configure>",
lambda e: main_canvas.configure(
    scrollregion=main_canvas.bbox("all")
    )
)

main_canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")

main_canvas.configure(yscrollcommand=scrollbar.set)

for i in range(100):
    f = Figure(figsize=(5,5), dpi=100)
    a = f.add_subplot(111)
    a.plot([1,2,3,4,5,6,7,8],[5,6,1,3,8,9,3,5])
    a.set_title("fig" + str(i))
    canvas = FigureCanvasTkAgg(f, 
                           master = scrollable_frame)
    canvas.draw()
    canvas.get_tk_widget().grid(row=i, column=0)

container.grid()
main_canvas.grid()
scrollbar.grid(row=0, column=1, sticky="nse")
container.mainloop()

I would like to generate lots of canvas on my scorllable frame, but it seems failed by maxiumn canvas size. Is there any method to fix it? code image


Solution

  • I'll take a guess and say that what you really want is a ScrolledText widget. Try this:

    import tkinter as tk
    from tkinter.scrolledtext import ScrolledText
    from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg,  NavigationToolbar2Tk)
    from matplotlib.figure import Figure
    
    root = tk.Tk()
    root.geometry('1500x800')
    scrollable_frame = ScrolledText(root)
    scrollable_frame.pack(expand=True, fill=tk.BOTH)
    
    for i in range(10):
        f = Figure(figsize=(5,5), dpi=100)
        a = f.add_subplot(111)
        a.plot([1,2,3,4,5,6,7,8],[5,6,1,3,8,9,3,5])
        a.set_title("fig" + str(i))
        canvas = FigureCanvasTkAgg(f)
        scrollable_frame.window_create(tk.END, window=canvas.get_tk_widget())
        scrollable_frame.insert(tk.END, '\n')
    
    root.mainloop()
    

    100 graphs will be very taxing no matter what, on the computer and the human. I think it would be better to design your program differently so that the graph is updated rather than scrolling through many graphs.