首页  >  文章  >  后端开发  >  如何在 Tkinter 中创建垂直滚动框架?

如何在 Tkinter 中创建垂直滚动框架?

Susan Sarandon
Susan Sarandon原创
2024-11-15 00:17:02583浏览

How to Create a Vertical Scrolling Frame in Tkinter?

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

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn