首頁 >後端開發 >Python教學 >如何在 Tkinter 中為一組小工具新增捲軸?

如何在 Tkinter 中為一組小工具新增捲軸?

Barbara Streisand
Barbara Streisand原創
2024-12-26 20:25:18879瀏覽

How to Add a Scrollbar to a Group of Widgets in Tkinter?

向Tkinter 中的一組小部件添加滾動條

概述

Tkinter 的滾動條功能僅限於特定小部件,不包括框架和根小部件。克服此限制需要其他方法。

框架嵌入畫布方法

  • 建立畫布小部件並將捲動條與
  • 包含標籤的框架畫布內的小部件。
  • 設定畫布的滾動區域以符合框架的大小。

物件導向的解決方案

import tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):

        # Initialize frame
        tk.Frame.__init__(self, parent)

        # Create canvas and scrollbar
        self.canvas = tk.Canvas(self, borderwidth=0, background="#ffffff")
        self.frame = tk.Frame(self.canvas, background="#ffffff")
        self.vsb = tk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=self.vsb.set)

        # Pack widgets
        self.vsb.pack(side="right", fill="y")
        self.canvas.pack(side="left", fill="both", expand=True)
        self.canvas.create_window((4,4), window=self.frame, anchor="nw", tags="self.frame")

        # Bind frame's <Configure> event to update scroll region
        self.frame.bind("<Configure>", self.onFrameConfigure)

        # Populate with data
        self.populate()

    def populate(self):
        for row in range(100):
            tk.Label(self.frame, text="%s" % row, width=3, borderwidth="1",
                     relief="solid").grid(row=row, column=0)
            t = "this is the second column for row %s" %row
            tk.Label(self.frame, text=t).grid(row=row, column=1)

    def onFrameConfigure(self, event):
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))

if __name__ == "__main__":
    root=tk.Tk()
    example = Example(root)
    example.pack(side="top", fill="both", expand=True)
    root.mainloop()

程式解決方案

import tkinter as tk

def populate(frame):
    for row in range(100):
        tk.Label(frame, text="%s" % row, width=3, borderwidth="1", 
                 relief="solid").grid(row=row, column=0)
        t = "this is the second column for row %s" %row
        tk.Label(frame, text=t).grid(row=row, column=1)

def onFrameConfigure(canvas):
    canvas.configure(scrollregion=canvas.bbox("all"))

root = tk.Tk()
canvas = tk.Canvas(root, borderwidth=0, background="#ffffff")
frame = tk.Frame(canvas, background="#ffffff")
vsb = tk.Scrollbar(root, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=vsb.set)

vsb.pack(side="right", fill="y")
canvas.pack(side="left", fill="both", expand=True)
canvas.create_window((4,4), window=frame, anchor="nw")

frame.bind("<Configure>", lambda event, canvas=canvas: onFrameConfigure(canvas))

populate(frame)

root.mainloop()
程式解決方法

以上是如何在 Tkinter 中為一組小工具新增捲軸?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn