I have been struggling to link the scrollbar widget to the figure embedded in the canvas widget. I have managed to display the scrollbar but it is not linked to the graph inside the canvas.
I attached below my simplified code.
import tkinter as tk
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg)
class AKP():
def __init__(self, the_window):
self.the_window = the_window
self.the_window.geometry("800x700")
self.the_window.resizable(False, False)
self.Main_Frame = tk.Frame(self.the_window)
self.Main_Frame.grid()
self.my_canvas = tk.Canvas(self.Main_Frame, width=1000, height=1000, scrollregion=(0,0, 600,1200), relief="sunk")
self.my_canvas.grid(row=1, column=0)
self.scrollY = tk.Scrollbar(self.Main_Frame, orient=tk.VERTICAL,
command=self.my_canvas.yview)
self.scrollY.grid(row=1, column=1, sticky=tk.NS)
self.my_canvas["yscrollcommand"] = self.scrollY.set
self.display_output()
def display_output(self):
self.fig = plt.Figure(figsize=(7, 9), dpi=100, facecolor="#D6EAF8")
self.ax = self.fig.add_subplot(111)
self.canvas = FigureCanvasTkAgg(self.fig, master=self.my_canvas)
self.canvas.get_tk_widget().grid(row=0, column=0)
var_text_1 = "Hello World"
self.ax.text(-0.1, 1.03, var_text_1, fontsize=12, fontweight="roman", fontfamily="fantasy")
if __name__ == "__main__":
my_window = tk.Tk()
application = AKP(my_window)
my_window.mainloop()
This is the method I use to add a Scrollbar in Tkinter
canvas = tk.Canvas(app)
canvas.pack(side="left", fill="both", expand=True)
# Create a frame to put in the canvas
main_frame = tk.Frame(canvas)
canvas.create_window((4,4), window=main_frame, anchor="nw") # This code fits the frame into the canvas window
*You don't need to make a Frame, if you want you can just put widgets straight into the Canvas.
# Scrollbar
def onFrameConfigure(canvas):
# Reset the scroll region to encompass the inner frame
canvas.configure(scrollregion=canvas.bbox("all"))
scrollbar = tk.Scrollbar(app, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=scrollbar.set)
scrollbar.pack(side="right", fill="y") # Displays scrollbar
main_frame.bind("<Configure>", lambda event, canvas=canvas: onFrameConfigure(canvas))
Now, everything you put in main_frame
will fit with the Scrollbar.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.