You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Python Tkinter中的按钮添加垂直与水平滚动条

Tkinter 横竖滚动条实现方案

核心实现逻辑

Tkinter 没有直接给普通容器加滚动条的功能,我们需要用「Canvas + 子Frame」的组合实现可滚动区域,结构如下:

  • 主窗口内先放横向、纵向两个滚动条,再放一个Canvas组件
  • 所有按钮放在Canvas内部的子Frame里,不要直接放在主窗口
  • 把滚动条和Canvas绑定,同时同步子Frame的尺寸到Canvas的滚动范围,滚动条就可以控制Canvas显示区域的偏移,带动里面的按钮一起滚动

改造后完整可运行代码

from tkinter import *

root = Tk()
root.geometry("555x350")

# -------------------------- 滚动区域核心配置开始 --------------------------
# 1. 创建纵向滚动条,绑定到窗口右侧
v_scroll = Scrollbar(root, orient=VERTICAL)
v_scroll.pack(side=RIGHT, fill=Y)
# 2. 创建横向滚动条,绑定到窗口底部
h_scroll = Scrollbar(root, orient=HORIZONTAL)
h_scroll.pack(side=BOTTOM, fill=X)

# 3. 创建Canvas组件,和两个滚动条绑定
canvas = Canvas(root, yscrollcommand=v_scroll.set, xscrollcommand=h_scroll.set)
canvas.pack(side=LEFT, fill=BOTH, expand=True)

# 4. 滚动条绑定Canvas的滚动方法
v_scroll.config(command=canvas.yview)
h_scroll.config(command=canvas.xview)

# 5. 创建放按钮的子Frame,放在Canvas里
btn_frame = Frame(canvas)
# 把Frame添加到Canvas的窗口组件中
canvas.create_window((0, 0), window=btn_frame, anchor="nw")

# 6. 同步子Frame的尺寸到Canvas的滚动范围,只要Frame里内容变化就更新滚动区域
def update_scrollregion(event):
    canvas.config(scrollregion=canvas.bbox("all"))
btn_frame.bind("<Configure>", update_scrollregion)

# 可选:添加鼠标滚轮滚动支持(Windows/macOS适配)
def on_mousewheel(event):
    canvas.yview_scroll(int(-1*(event.delta/120)), "units")
canvas.bind_all("<MouseWheel>", on_mousewheel)
# -------------------------- 滚动区域核心配置结束 --------------------------

# 所有按钮现在放到btn_frame里,不要放root,其他坐标参数和你原来的写法完全一致
b = Button(btn_frame, text="Sample button 1")
b.place(x=0, y=0)

b = Button(btn_frame, text="Sample button 1")
b.place(x=0, y=30)

b = Button(btn_frame, text="Sample button 1")
b.place(x=0, y=90)

b = Button(btn_frame, text="Sample button 1")
b.place(x=0, y=160)

b = Button(btn_frame, text="Sample button 1")
b.place(x=0, y=334)

b = Button(btn_frame, text="Sample button 1")
b.place(x=120, y=0)

b = Button(btn_frame, text="Sample button 1")
b.place(x=230, y=0)

b = Button(btn_frame, text="Sample button 1")
b.place(x=472, y=0)

root.mainloop()

关键部分说明

  • 所有你需要滚动的内容都要放在btn_frame里,不能直接放在主窗口,否则不会跟着滚动
  • update_scrollregion函数的作用是自动检测子Frame里所有内容的总尺寸,设置滚动的最大范围,你后续新增按钮不需要手动修改滚动范围
  • 如果你要调整可视区域的大小,只需要修改主窗口的geometry参数即可,滚动条会自动适配显示

内容的提问来源于stack exchange,提问作者Jashodhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 19:57:03