Search code examples
pythontkinterttk

Prevent a function being called twice when a user double-clicks a button?


I have developed a user interface in tkinter/ttk that uses the standard ttk.Button widget to call various functions using the 'command' argument. The problem is that if a user double-clicks a button the function is called twice. This causes all sorts of problems. The double-click event is not bound to anything so is there a way to disable the second single-click? I've tried time.sleep() and after() at the start of the function definition but I haven't found a way to make it work. Do I need to manually bind each function to a click for each button and reassign the event handler? Any straightforward way to do ignore double-clicks across the board???


Solution

  • Just tell the button's callback function (its command) to disable the button, then put it back to normal after a brief period (200ms here).

    def callback(self):
        self.my_button.config(state=tk.DISABLED)
        self.root.after(200, lambda: self.my_button.config(state=tk.NORMAL))
        # other actions
    

    As Bryan points out, it's better and simpler to just wait until the function is finished (unless you just wanted to guard against accidental double-clicks and are okay with the function being called again before it's necessarily finished):

    def callback(self):
        self.my_button.config(state=tk.DISABLED)
        # other actions
        self.my_button.config(state=tk.NORMAL)
    

    This sample code assumes an import of import tkinter as tk, an OO app structure, a button called self.my_button, a callback function called self.callback, and a root object called self.root.