TkInter,滑块:如何仅在迭代完成时触发事件? [英] TkInter, slider: how to trigger the event only when the iteraction is complete?

查看:33
本文介绍了TkInter,滑块:如何仅在迭代完成时触发事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用滑块更新我的可视化效果,但每次移动滑块时都会发送命令 updateValue,即使是中间值也是如此.

I'm using the slider to update my visualization, but the command updateValue is sent everytime I move the slider thumb, even for intermediate values.

相反,我只想在释放鼠标按钮并且交互完成时触发它.

Instead I want to trigger it only when I release the mouse button and the interaction is complete.

self.slider = tk.Scale(self.leftFrame, from_=0, to=256, orient=tk.HORIZONTAL, command=updateValue)

如何在交互结束时只触发一次该功能?

How can I trigger the function only once, when the interaction is ended ?

推荐答案

你不能.

您可以做的是让您的命令使用after"将任何实际工作延迟一小段时间.每次调用您的命令时,取消任何挂起的工作并重新安排工作.根据您的实际要求,半秒延迟可能就足够了.

What you can do instead is have your command delay any real work for a short period of time using 'after'. Each time your command is called, cancel any pending work and reschedule the work. Depending on what your actual requirements are, a half second delay might be sufficient.

另一种选择是不使用内置命令功能,而是使用自定义绑定.这可能需要大量工作才能完全正确,但如果您确实需要细粒度控制,则可以做到.不要忘记,除了鼠标之外,还可以使用键盘与小部件进行交互.

Another choice is to not use the built-in command feature and instead use custom bindings. This can be a lot of work to get exactly right, but if you really need fine grained control you can do it. Don't forget that one can interact with the widget using the keyboard in addition to the mouse.

以下是一个简短示例,展示了如何安排在半秒内完成的工作:

Here's a short example showing how to schedule the work to be done in half a second:

import Tkinter as tk

#create window & frames
class App:
    def __init__(self):
        self.root = tk.Tk()
        self._job = None
        self.slider = tk.Scale(self.root, from_=0, to=256, 
                               orient="horizontal", 
                               command=self.updateValue)
        self.slider.pack()
        self.root.mainloop()

    def updateValue(self, event):
        if self._job:
            self.root.after_cancel(self._job)
        self._job = self.root.after(500, self._do_something)

    def _do_something(self):
        self._job = None
        print "new value:", self.slider.get()

app=App()

这篇关于TkInter,滑块:如何仅在迭代完成时触发事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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