python - How to trigger a callback function when a button is pressed for a long time -
how can create callback long-time-pressed button? example, want save new value when press button more 2 seconds. there way this?
b3=tkinter.button(frames, text='1',font='agency 50', relief='groove',bd=5,width= 3, height=1) b3.bind("<button-1>", savep1) b3.bind("<buttonrelease-1>",savep11) def savep1(event): dur() if duration > 2: update1() clock[0]=time.time() else: connection=sqlite3.connect('joimax.db') cursor=connection.cursor() sql = "select * speicherplatz name='save1'" cursor.execute(sql) dsatz in cursor: scv.set(str(dsatz[2])) direction.set(dsatz[1]) connection.close() grafik() print(' speed: ', str(dsatz[2]))
just said, tried judge duration of 2 actions. there errors.
exception in tkinter callback traceback (most recent call last): file "c:\python34\lib\tkinter\__init__.py", line 1533, in __call__ return self.func(*args) file "c:\python34\Übung\gui4.py", line 147, in savep1 if duration > 2: nameerror: name 'duration' not defined
update: solved problem yesterday. use after
, , here code. causes little bit slow down of skript, better nothing.
def loop1(): global duration if duration>2: duration=0 update1() else: if press==false: duration=0 do1() else: print('loop', duration) duration=duration+timeit.timeit()+0.25 main.after(250, loop1) def savep1(event): global press press=true main.after(0,loop1) def savep11(event): global press press=false
i don't know how functions work here's quick example made should illustrate way this.
the first function call time.clock()
, store global value (so second function can access it). function called when button first clicked.
the second function call time.clock()
, calculate difference between , initial time.
if time greater 2.0 call third function; "save new value". used show done @ times >= 2.0 seconds
if time less 2 seconds print message time.
here's example code, hope solve problem.
from tkinter import * import tkmessagebox import time root = tk() starttime = 0 def dostuff(): global starttime starttime = time.clock() def domore(): total = time.clock() - starttime if total >= 2.0: doevenmore(total) else: print("sorry, %5f seconds." %total) def doevenmore(total): # whatever after 2 seconds (save new value) tkmessagebox.showinfo("congrats", "you held button down %.5f seconds!" %total) b = button(root, text = "try me", justify = center) b.pack() # button down: start time b.bind("<button-1>", lambda event: dostuff()) # button up: end time, check if function or not b.bind("<buttonrelease-1>", lambda event: domore()) root.mainloop()
Comments
Post a Comment