如何在长按按钮时触发回调功能

时间:2015-07-22 15:16:59

标签: python python-3.x tkinter

如何为长按按钮创建回调?例如,当我按下按钮超过2秒时,我想保存一个新值。有什么好办法吗?

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 * FROM Speicherplatz WHERE name='save1'"
    cursor.execute(sql)
    for dsatz in cursor:
        scv.set(str(dsatz[2]))
        direction.set(dsatz[1])
        connection.close()
        grafik()
        print(' speed: ', str(dsatz[2]))

就像我说的那样,我试图判断两个动作的持续时间。但总有错误。

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' is not defined

更新:我昨天解决了这个问题。只需使用after,这是代码。它会导致skript一点点减速,但总比没有好。

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

1 个答案:

答案 0 :(得分:0)

我不太了解你的功能是如何工作的,但这里有一个简单的例子我应该说明你可以做到这一点。

第一个函数将调用time.clock()并将其存储为全局值(以便第二个函数可以访问它)。首次单击该按钮时会调用此函数。

第二个函数将调用time.clock()并计算此值与初始时间之间的差值。

如果此时间大于2.0,我会调用第三个函数;这可能是你“保存新价值”的地方。我只是用它来表明它只会在&gt; = 2.0秒

时完成

如果时间少于2秒,我只需打印带有时间的信息。

以下是示例代码,希望它能帮助您解决问题。

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, only %5f seconds." %total)

def doEvenMore(total):

    # This will be whatever you do after 2 seconds (save new value)
    tkMessageBox.showinfo("Congrats", "You held a button down for %.5f seconds!" %total)

b = Button(root, text = "Try Me", justify = CENTER)
b.pack()
# Button down: get a start time
b.bind("<Button-1>", lambda event: doStuff())
# Button up: get end time, check if you do the function or not
b.bind("<ButtonRelease-1>", lambda event: doMore())

root.mainloop()
相关问题