Skip to content
Advertisement

How can I condition a button click not to execute, if the click is not immediately released in Python?

What I want the button not to do is that the linked function is executed if the user holds the click and when he releases it the function does not execute, because I have an event linked to the button bind to move the window as it doesn’t have the window manager and the app is mostly just buttons. Thank you very much for all the help you can give me.

from tkinter import *

def destroy1():
    print('Hellow')

root = Tk()
frm = Frame(root, bg='gray')
frm.pack()
btn = Button(frm, text='Closed', command= destroy1)
btn.pack()

root.mainloop()

Advertisement

Answer

I don’t think that can be done easily, but if you really want to do it:

from tkinter import *
import time

FLAG = None

def on_press(x):
    global FLAG
    FLAG = time.time()

def on_release(x):
    if FLAG is None: return
    if time.time() - FLAG > 2: root.destroy()
    FLAG = None


root = Tk()

frm = Frame(root, bg='gray')
frm.pack()
btn = Button(frm, text='Closed')
btn.pack()

btn.bind('<ButtonPress>', on_press)
btn.bind('<ButtonRelease>', on_release)

root.mainloop()

destroys only if the button is hold for > 2 seconds

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement