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

Tkinter混合使用横竖PanedWindow时如何实现上下垂直窗格分隔线联动

解决Tkinter PanedWindow四格布局垂直分隔线联动问题

实现思路

  • 上下两行的垂直分隔线分属两个独立的水平方向PanedWindow实例,只要保持两个实例的首个分隔线位置一致即可实现联动
  • 通过绑定鼠标拖动和释放事件,触发时将当前拖动的分隔线位置同步到另一个PanedWindow上

修正后完整代码

from tkinter import *

def sync_sash(event, source_pane, target_pane):
    # 读取源窗格第一个分隔线的位置,同步设置到目标窗格
    current_pos = source_pane.sashpos(0)
    target_pane.sashpos(0, current_pos)

master = Tk()
master.geometry("400x400")

# 主垂直PanedWindow,负责水平分隔线
main_panel = PanedWindow(orient=VERTICAL, bd=2, relief="solid", bg="black")
main_panel.pack(fill="both", expand=1)

# 上半部分水平PanedWindow,负责上半部分垂直分隔线
top_pane = PanedWindow(main_panel, bd=1, relief="solid", bg="black")
top_left_label = Label(top_pane, text= "Left-top")
top_pane.add(top_left_label)
top_right_label = Label(top_pane, text= "Right-top")
top_pane.add(top_right_label)
main_panel.add(top_pane)

# 下半部分水平PanedWindow,负责下半部分垂直分隔线
bottom_pane = PanedWindow(main_panel, bd=1, relief="solid", bg="black")
bottom_left_label = Label(bottom_pane, text= "Left-bottom")
bottom_pane.add(bottom_left_label)
bottom_right_label = Label(bottom_pane, text= "Right-bottom")
bottom_pane.add(bottom_right_label)
main_panel.add(bottom_pane)

# 绑定事件实现分隔线同步
top_pane.bind('<B1-Motion>', lambda e: sync_sash(e, top_pane, bottom_pane))
top_pane.bind('<ButtonRelease-1>', lambda e: sync_sash(e, top_pane, bottom_pane))
bottom_pane.bind('<B1-Motion>', lambda e: sync_sash(e, bottom_pane, top_pane))
bottom_pane.bind('<ButtonRelease-1>', lambda e: sync_sash(e, bottom_pane, top_pane))

mainloop()

效果说明

运行代码后,拖动任意一条垂直分隔线,另一条会同步移动,不会出现错位问题,水平贯穿的分隔线可以独立拖动调整上下高度,不影响垂直分隔线的联动逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 05:36:04