Anthony
Anthony

Reputation: 661

Function not lauching upon key press

So I have this code in Python:

class Chronometre(Frame):                                       

    def __init__(self, parent=None, **kw):
        Frame.__init__(self, parent, kw)
        self._start = 0.0        
        self._elapsedtime = 0.0
        self._running = 0
        self.timestr = StringVar()               
        self.makeWidgets()    

    def _update(self):
        self._elapsedtime = time.time() - self._start
        self._setTime(self._elapsedtime)
        self._timer = self.after(50, self._update)

    def Start(self):                                                     
        if not self._running:            
            self._start = time.time() - self._elapsedtime
            self._update()
            self._running = 1        

    def Stop(self):                                    
        if self._running:
            self.after_cancel(self._timer)            
            self._elapsedtime = time.time() - self._start    
            self._setTime(self._elapsedtime)
            self._running = 0

    def Reset(self):                             
        self._start = time.time()         
        self._elapsedtime = 0.0    
        self._setTime(self._elapsedtime)

def Clavier(event):
    print(event.keysym)
    if event.keysym == 'a' :
        sw = Chronometre()
        sw.Start()
        sv = Chronometre()
        sv.Start()
    if event.keysym == 'z' :
        sw = Chronometre()
        sw.Stop()
    if event.keysym == 'e' :
        sv = Chronometre()
        sv.Stop()
    if event.keysym == 'r' :
        sw = Chronometre()
        sw.Reset()
        sv = Chronometre()
        sv.Reset()

def main():
    root = Tk()

    root.bind("<Key>",Clavier)

A friend of mine is trying to launch a function upon hitting a key, but it doesn't launch the function. Does anybody know why this would happen? I know the program goes into the if statement but it won't launch the function.

Could it be because of the fact that it is in a class?

Upvotes: 0

Views: 58

Answers (2)

user4171906
user4171906

Reputation:

First, you have to run the Tkinter mainloop for it to do anything, like catch keys

root.mainloop()

Second, the Start() function has variables that have not been declared, so you will get an error the first time through, i.e. self._running and self._elapsedtime. Also the function _setTime() has not been declared.

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599470

You don't seem to be instantiating your classes, or calling their methods.

if event.keysym == 'a' :
    sw = Chronometre()
    sw.Start()

and so on.

Upvotes: 4

Related Questions