滾動一組小部件

當視窗包含許多小部件時,它們可能都不可見。但是,視窗(Tk 或 Toplevel 例項)和 Frame 都不可滾動。使視窗內容可滾動的一種解決方案是將所有視窗小部件放在框架中,然後使用 create_window 方法將此框架嵌入到畫布中。

canvas = tk.Canvas(parent)
scroll_y = tk.Scrollbar(parent, orient="vertical", command=canvas.yview)

frame = tk.Frame(canvas)
# group of widgets
for i in range(20):
    tk.Label(frame, text='label %i' % i).pack()
# put the frame in the canvas
canvas.create_window(0, 0, anchor='nw', window=frame)
# make sure everything is displayed before configuring the scrollregion
canvas.update_idletasks()

canvas.configure(scrollregion=canvas.bbox('all'), 
                 yscrollcommand=scroll_y.set)
                 
canvas.pack(fill='both', expand=True, side='left')
scroll_y.pack(fill='y', side='right')