954,545 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

Timing simultaneous key pushes/mouse clicks in Tkinter

0
By Tony Veijalainen on Dec 17th, 2011 5:44 am

This code is based on code from series of programs 'Thinking in tkinter'

This code is not perfect, especially it does not recognize key release when mouse moves out of button area during push. Leave event could also be captured for that to stop the event in that case.

from Tkinter import *
from time import clock
from functools import partial

class KeyFrame(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.master = master
        self.start = dict()

        self.bind('<a>', partial(self.process, id='a'))
        self.bind('<KeyRelease-a>', partial(self.end_note, id='a'))

        self.button1 = Button(master, command=partial(self.end_note, id='C'))
        self.button1.configure(text="C")
        self.button1.pack()
        self.button1.bind_all("<Button-1>", partial(self.process, id='C'))

        self.label = Label(text='"a" key and/or push "C" button by mouse')
        self.label.pack()

        self.focus_force()
        self.pack(side=LEFT, expand=TRUE)

    def process(self, event=None, id=None):
        if not id in self.start:
            self.start[id] = clock()
            self.start_note(id=id)

    def start_note(self, event=None, id=None):
        print "Playing note", id
        self.start[id] = clock()

    def end_note(self, event=None, id=None):
        if id in self.start:
            self.label['text'] += "\n%s, duration: %.3f" % (id,(clock() - self.start[id]))
            del self.start[id]


mainw = Tk()
KeyFrame(mainw)
mainw.mainloop()

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: