Timing simultaneous key pushes/mouse clicks in Tkinter

TrustyTony 0 Tallied Votes 461 Views Share

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.bind_all("<Button-1>", partial(self.process, id='C'))

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

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

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

    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()