一起滚动多个 Tkinter 列表框 [英] Scrolling multiple Tkinter listboxes together
问题描述
我有多个 Tkinter 列表框,我使用单个滚动条将它们一起滚动,但我也希望它们一起滚动以在任何列表框上进行鼠标滚轮活动.
I have multiple Tkinter listboxes that I have scrolling together using a single scrollbar, but I'd ALSO like them to scroll together for mousewheel activity over any of the listboxes.
如何做到这一点?
我当前的代码基于这里讨论的最后一个模式:http://effbot.org/tkinterbook/listbox.htm 仅使用滚动条时效果很好,但使用鼠标滚轮时列表框独立滚动.
My current code is based on the last pattern discussed here: http://effbot.org/tkinterbook/listbox.htm It works fine when using only the scrollbar, but the listboxes scroll independently when the mousewheel is used.
推荐答案
解决问题的方法与将两个小部件连接到单个滚动条的方法几乎相同:为鼠标滚轮创建自定义绑定并使这些绑定同时影响两者列表框,而不仅仅是一个.
Solve the problem pretty much the same way as you did to connect the two widgets to a single scrollbar: create custom bindings for the mousewheel and have those bindings affect both listboxes rather than just one.
唯一真正的技巧是知道你会根据平台获得不同的鼠标滚轮事件:windows 和 Mac 获得
事件,Linux 获得
和
事件.
The only real trick is knowing that you get different events for the mousewheel depending on the platform: windows and the Mac gets <MouseWheel>
events, linux gets <Button-4>
and <Button-5>
events.
这是一个例子,在我的 Mac 上用 python 2.5 测试过:
Here's an example, tested on my Mac with python 2.5:
import Tkinter as tk
class App:
def __init__(self):
self.root=tk.Tk()
self.vsb = tk.Scrollbar(orient="vertical", command=self.OnVsb)
self.lb1 = tk.Listbox(self.root, yscrollcommand=self.vsb.set)
self.lb2 = tk.Listbox(self.root, yscrollcommand=self.vsb.set)
self.vsb.pack(side="right",fill="y")
self.lb1.pack(side="left",fill="x", expand=True)
self.lb2.pack(side="left",fill="x", expand=True)
self.lb1.bind("<MouseWheel>", self.OnMouseWheel)
self.lb2.bind("<MouseWheel>", self.OnMouseWheel)
for i in range(100):
self.lb1.insert("end","item %s" % i)
self.lb2.insert("end","item %s" % i)
self.root.mainloop()
def OnVsb(self, *args):
self.lb1.yview(*args)
self.lb2.yview(*args)
def OnMouseWheel(self, event):
self.lb1.yview("scroll", event.delta,"units")
self.lb2.yview("scroll",event.delta,"units")
# this prevents default bindings from firing, which
# would end up scrolling the widget twice
return "break"
app=App()
这篇关于一起滚动多个 Tkinter 列表框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!