将 Tkinter 滚动条跳转到某个小部件 [英] Jump a Tkinter scrollbar to a certain widget

查看:29
本文介绍了将 Tkinter 滚动条跳转到某个小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Tkinter GUI 中添加了一些滚动条功能

I have added some scrollbar functionality to my Tkinter GUI like so

self.canvas = tk.Canvas(self.baseframe)
self.scrollbar = tk.Scrollbar(self.baseframe, orient="vertical", command=self.canvas.yview)
self.scrollable = tk.Frame(self.canvas)
self.scrollable.bind("<Configure>", lambda e: self.canvas.configure(scrollregion=self.canvas.bbox("all")))
self.canvas.create_window((0, 0), window=self.scrollable, anchor="n")
self.canvas.configure(yscrollcommand=self.scrollbar.set)
self.canvas.bind_all("<MouseWheel>", self._mousescroll)

我已经将 _mousecroll() 定义为

    def _mousescroll(self, event):
        """mouse wheel scroll callback"""
        # Divide the event.delta by some value to effect the scrolling speed
        self.canvas.yview_scroll(int(-1*(event.delta/120)), "units")

运行良好.

然后我将一些 tkLabelFrame 小部件添加到滚动区域(它们本身包含显示内容的小部件 - 与此问题无关).整个滚动功能运行良好.

I then add some tkLabelFrame widgets to the scroll area (which themselves contain widgets displaying stuff - not relevant for this question). The whole scrolling functionality works really well.

在我的 GUI 的其他部分,我希望用户能够通过单击按钮跳转"到滚动区域中的特定点.实际上会自动将滚动区域滚动到这一点.这可能吗?我可以完全控制 GUI 代码,因此我可以将标签添加到 tkLabelFrames 列表中,将它们存储在某种列表/字典中,以便可以轻松查找它们……诸如此类?

In other part of my GUI, I would like the user to be able to "jump" to a specific point in the scroll area, on a button click. In effect automatically scroll the scroll area to this point. Is this possible? I have full control over the GUI code so I can add labels to the list of tkLabelFrames, store them in some kind of list/dictionary so they can easily be looked up...something like that?

注意:添加到滚动区域的 tkLabelFrames 数量是动态的,因此某种绝对的跳转到这么多像素"可能不起作用.我希望可能有某种滚动到带有此标签/属性等的小部件"功能.任何帮助表示赞赏.谢谢.

Note: The number of tkLabelFrames that are added to the scroll area is dynamic so some kind of absolute "jump to this many pixels" would probably not work. I was hoping there might be some kind of "scroll to a widget with this label/attribute etc.." functionality. Any help appreciated. Thanks.

推荐答案

对于我的特定场景,可滚动区域内的小部件的高度都相同,因此我能够使用简单的分数滚动到正确的位置.

For my particular scenario, the widgets within the scrollable area where all the same height, so I was able to use a simple fraction to scroll to the correct place.

添加一个按钮,回调这样的方法对我有用:

Adding a button, with a callback to a method like this worked for me:

def scrollto(self, idx):
    # Where self.frames is the list of tkLabelFrame objects.
    fraction = float(idx/len(self.frames))

    # self.canvas is my scrollable canvas
    self.canvas.yview_moveto(fraction)

这篇关于将 Tkinter 滚动条跳转到某个小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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