Reputation: 61
Still quite new at python , i'm learning tkinter. I would like to use keyboard events rather than mouse events for some fonction. However keyboard events do not work although mouse events do. here is a very simple example of what is not working. Using button 1 with the mouse and pressing key 'z on the keyboard should do the same, but the keyboard does nothing. I have tried to read tkinter documentation but didn't find the answer.
thanks for your help
from tkinter import *
class Pipi(Frame):
def __init__(self,master=None):
Frame.__init__(self,width=400,height=400,bg='red')
self.pack()
self.bind("<z>",self.do)
self.bind("<Button-1>", self.do)
def do(self,event):
print('la vie est belle')
root=Tk()
Pipi(root)
root.mainloop()
Upvotes: 1
Views: 1891
Reputation: 15325
This is due to Frame
widget not having the focus. With the mouse event, it works seemingly different. There can be a couple of workarounds:
To achieve the first, simply add:
self.focus_set()
somewhere inside __init__
.
To achieve the second, replace:
self.bind("<z>",self.do)
with:
self.master.bind('<z>', self.do)
Upvotes: 3