滚动一组小部件

当窗口包含许多小部件时,它们可能都不可见。但是,窗口(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')