tags:

views:

26

answers:

1

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 ?

A: 

You can't.

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()
Bryan Oakley
@Bryan Oakley Ok, what's the best way to have a 0.5 delay ?
Patrick
@Patric: I've edited the answer to include an example
Bryan Oakley
@Bryan Oakley Thanks, I get this error: AttributeError: 'str' object has no attribute '_job'
Patrick
@Patric: I can't debug your code for you, especially without seeing it. Think about what the error message is telling you, this is not a hard problem. You are trying to access the attribute "_job" from some object. That object has no such attribute. Thus, either you're using the wrong object, or your object is somehow broken.
Bryan Oakley
@Bryan Oakley ok thanks
Patrick