一起滚动多个Tkinter列表框 [英] Scrolling multiple Tkinter listboxes together

查看:238
本文介绍了一起滚动多个Tkinter列表框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个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获得<MouseWheel>事件,Linux获得<Button-4><Button-5>事件.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆