首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何实现Python tkinter中三个Listbox的同步滚动条?

如何实现Python tkinter中三个Listbox的同步滚动条?

提问于 2024-08-28 11:02:58
回答 0关注 0查看 18

在Python的tkinter库中,为三个Listbox控件分别配置独立的Scrollbar控件,同时确保当一个Listbox滚动时,其他两个Listbox能够同步滚动。

现在我主要的问题就是用鼠标滚动一个Listbox时滚动速度总会快于其他两个。还有就是拉动Scrollbar控件时无法同步滚动。(更进一步:实现一个开关控制是否开启同步滚动)

下面是我的代码:

代码语言:python
代码运行次数:0
复制
import tkinter as tk
from tkinter import ttk

def on_scroll(event, *listboxes):
    print(event, event.delta)
    # 根据滚动事件获取滚动条的滚动位置
    x = event.x
    y = event.y
    if event.num == 5 or event.delta > 0:
        # 向上滚动或鼠标滚轮向上滚动
        y = -1
    elif event.num == 4 or event.delta < 0:
        # 向下滚动或鼠标滚轮向下滚动
        y = 1
    # # 更新所有Listbox的滚动位置
    for lbox in listboxes:
        lbox.yview_scroll(int(-1*(event.delta/120)), "units")

def create_listbox_with_scrollbar(master, listbox, scrollbar):
    # 将滚动条的command设置为更新Listbox的滚动位置
    scrollbar.config(command=lambda *args: listbox.yview(*args))
    # 将Listbox的滚动命令设置为滚动条的滚动函数
    listbox.config(yscrollcommand=lambda *args: scrollbar.set(*args))
    # 将Listbox和滚动条添加到主窗口
    listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
    scrollbar.pack(side=tk.LEFT, fill=tk.Y)

def create_app():
    root = tk.Tk()
    root.title("同步滚动的Listbox")

    # 创建三个Listbox和它们的滚动条
    listbox1 = tk.Listbox(root, width=20, height=10)
    scrollbar1 = ttk.Scrollbar(root, orient="vertical", command=listbox1.yview)

    listbox2 = tk.Listbox(root, width=20, height=10)
    scrollbar2 = ttk.Scrollbar(root, orient="vertical", command=listbox2.yview)

    listbox3 = tk.Listbox(root, width=20, height=10)
    scrollbar3 = ttk.Scrollbar(root, orient="vertical", command=listbox3.yview)

    # 将Listbox和滚动条添加到主窗口
    create_listbox_with_scrollbar(root, listbox1, scrollbar1)
    create_listbox_with_scrollbar(root, listbox2, scrollbar2)
    create_listbox_with_scrollbar(root, listbox3, scrollbar3)

    # 绑定滚动事件到所有Listbox
    for lbox in [listbox1, listbox2, listbox3]:
        lbox.bind("<MouseWheel>", lambda event: on_scroll(event, listbox1, listbox2, listbox3))

    # 填充一些示例数据到Listbox
    for i in range(100):
        listbox1.insert(tk.END, f"Item 1 {i}")
        listbox2.insert(tk.END, f"Item 2 {i}")
        listbox3.insert(tk.END, f"Item 3 {i}")

    root.mainloop()

create_app()

感谢!!!

回答

和开发者交流更多问题细节吧,去 写回答
相关文章

相似问题

相关问答用户
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档