Tkinter Scrollbar for Frame
Issue:
Create a vertical scrollbar for a frame that automatically activates when the frame's content exceeds its height, allowing multiple labels to be displayed within the frame.
Implementation:
Here's a sample code that encapsulates a scrollable frame:
# VerticalScrolledFrame class allows vertical scrolling within a frame class VerticalScrolledFrame(ttk.Frame): def __init__(self, parent, *args, **kw): # Create a canvas and vertical scrollbar vscrollbar = ttk.Scrollbar(self, orient=VERTICAL) vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE) canvas = tk.Canvas(self, bd=0, highlightthickness=0, yscrollcommand=vscrollbar.set) canvas.pack(side=LEFT, fill=BOTH, expand=TRUE) vscrollbar.config(command=canvas.yview) # Create an inner frame for content, scrollable within the canvas self.interior = interior = ttk.Frame(canvas) interior_id = canvas.create_window(0, 0, window=interior, anchor=NW) # Synchronize frame and canvas dimensions def _configure_interior(event): size = (interior.winfo_reqwidth(), interior.winfo_reqheight()) canvas.config(scrollregion="0 0 %s %s" % size) if interior.winfo_reqwidth() != canvas.winfo_width(): canvas.config(width=interior.winfo_reqwidth()) interior.bind('<Configure>', _configure_interior) def _configure_canvas(event): if interior.winfo_reqwidth() != canvas.winfo_width(): canvas.itemconfigure(interior_id, width=canvas.winfo_width()) canvas.bind('<Configure>', _configure_canvas)
Advantages of this Implementation:
Usage:
# Example usage app = tk.Tk() my_frame = VerticalScrolledFrame(app) my_frame.pack() for i in range(50): ttk.Label(my_frame.interior, text=i).grid(row=i, column=0) # Grid method ensures proper layout of labels app.mainloop()
Das obige ist der detaillierte Inhalt vonWie erstelle ich in Tkinter einen scrollbaren Rahmen mit automatischer Aktivierung?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!