框架的 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中文网其他相关文章!