Rumah >pembangunan bahagian belakang >Tutorial Python >Bagaimana untuk Menambah Bar Tatal pada Kumpulan Widget di Tkinter?
Gambaran Keseluruhan
Fungsi bar skrol Tkinter terhad kepada widget tertentu, tidak termasuk Bingkai dan widget akar. Mengatasi had ini memerlukan pendekatan alternatif.
Pendekatan Bingkai-Terbenam-dalam-Kanvas
Penyelesaian Berorientasikan Objek
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()
Prosedur Penyelesaian
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()
Atas ialah kandungan terperinci Bagaimana untuk Menambah Bar Tatal pada Kumpulan Widget di Tkinter?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!