在Python的tkinter
库中,为三个Listbox
控件分别配置独立的Scrollbar
控件,同时确保当一个Listbox
滚动时,其他两个Listbox
能够同步滚动。
现在我主要的问题就是用鼠标滚动一个Listbox时滚动速度总会快于其他两个。还有就是拉动Scrollbar控件时无法同步滚动。(更进一步:实现一个开关控制是否开启同步滚动)
下面是我的代码:
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()
感谢!!!
相似问题