TkInter,滑块:如何仅在迭代完成时触发事件?

编程入门 行业动态 更新时间:2024-10-23 15:22:20
本文介绍了TkInter,滑块:如何仅在迭代完成时触发事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在使用滑块更新我的可视化效果,但每次移动滑块时都会发送命令 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 08:46:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1391975.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:滑块   事件   迭代   TkInter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!