為Tkinter 框架使用垂直可捲動框架
您為包含多個標籤的框架尋找一個捲軸,當框架高度達到時自動啟動被超過。以下是使用自訂 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)
現在,您可以使用此 VerticalScrolledFrame 作為框架來添加標籤並啟動自動滾動:
# 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)
以上是如何在 Tkinter 中建立垂直滾動框架?的詳細內容。更多資訊請關注PHP中文網其他相關文章!