框架的Tkinter 捲軸
問題:
為框架建立一個垂直滾動條當框架的內容超過其高度時自動激活,允許在框架內顯示多個標籤
實現:
這是一個封裝可滾動框架的範例程式碼:
# 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)
此實現的優點:
用法:
# 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()
以上是如何在 Tkinter 中建立自動啟動的可捲動框架?的詳細內容。更多資訊請關注PHP中文網其他相關文章!