Using a Vertical Scrollable Frame for a Tkinter Frame
You seek a scrollbar for a frame containing multiple labels that automatically activates when the frame height is exceeded. Here's how you can achieve this using a custom VerticalScrolledFrame:
# VerticalScrolledFrame allows for вертикальное прокрутка in a frame import tkinter as tk import tkinter.ttk as ttk class VerticalScrolledFrame(ttk.Frame): def __init__(self, parent, *args, **kw): ttk.Frame.__init__(self, parent, *args, **kw) # Components for scrolling vscrollbar = ttk.Scrollbar(self, orient=VERTICAL) vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE) self.canvas = tk.Canvas(self, bd=0, highlightthickness=0, yscrollcommand=vscrollbar.set) self.canvas.pack(side=LEFT, fill=BOTH, expand=TRUE) vscrollbar.config(command=self.canvas.yview) # Initialize view position self.canvas.xview_moveto(0) self.canvas.yview_moveto(0) # Scrollable area self.interior = interior = ttk.Frame(self.canvas) interior_id = self.canvas.create_window(0, 0, window=interior, anchor=NW) # Events to handle changes def _configure_interior(event): size = (interior.winfo_reqwidth(), interior.winfo_reqheight()) self.canvas.config(scrollregion="0 0 %s %s" % size) if interior.winfo_reqwidth() != self.canvas.winfo_width(): self.canvas.config(width=interior.winfo_reqwidth()) interior.bind('<<Configure>>', _configure_interior) def _configure_canvas(event): if interior.winfo_reqwidth() != self.canvas.winfo_width(): self.canvas.itemconfigure(interior_id, width=self.canvas.winfo_width()) self.canvas.bind('<<Configure>>', _configure_canvas)
Now, you can use this VerticalScrolledFrame as your frame to add labels and activate autoscrolling:
# Frame with scrolling frame = VerticalScrolledFrame(root) # Add labels for i in range(50): Label(frame.interior,text=i).grid(row=i,column=0) Label(frame.interior,text="my text"+str(i)).grid(row=i,column=1) Label(frame.interior,text="..........").grid(row=i,column=2)
The above is the detailed content of How to Create a Vertical Scrolling Frame in Tkinter?. For more information, please follow other related articles on the PHP Chinese website!