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
相关产品推荐
相关产品推荐

