Keyboard shortcuts with tkinter in Python 3 Keyboard shortcuts with tkinter in Python 3 tkinter tkinter

Keyboard shortcuts with tkinter in Python 3


consider reading (http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm)

you have to bind your widget to an event to your function:

Keyboard events are sent to the widget that currently owns the keyboard focus. You can use the focus_set method to move focus to a widget:

Capturing keyboard events

from Tkinter import *root = Tk()def key(event):    print "pressed", repr(event.char)def callback(event):    frame.focus_set()    print "clicked at", event.x, event.yframe = Frame(root, width=100, height=100)frame.bind("<Key>", key)frame.bind("<Button-1>", callback)frame.pack()root.mainloop()

If you run this script, you’ll find that you have to click in the frame before it starts receiving any keyboard events.

I followed this guide to implement a ctrl+f binding to one of my functions a while ago:

toolmenu.add_command(label="Search Ctrl+f", command=self.cntrlf)root.bind('<Control-f>', self.searchbox)def cntrlf(self, event):    self.searchbox()

for your file menu, you might want to consider implementing accelerators:

menubar.add_cascade(label="File", menu=fileMenu)fileMenu.add_command(label="Exit", command=quit, accelerator="Ctrl+Q")config(menu=menubar) 

for Menu options remember to use ALT followed by the first letter of the OptionName

file Menu = ALT followed by fTool Menu = ALT followed by tand so on

hope this provides usefull


is there a way for the frame to receive events without clicking on the frame? If i scrolled over to the frame to click on it, i have already used time to get over there, might as well just click on the button as opposed to use the shortcut key.

The answer is to bind the whole root/master/window to a keybinding so that whenever you press that key a function is called which does your task.

import sysfrom tkinter import *root=Tk()Menu_bar = Menu(root)m1 = Menu(Menu_bar, tearoff=0)m1.add_command(label="exit", command=sys.quit)Menu_bar.add_cascade(label="file", menu=m1)root.bind("<Alt_L><f>", sys.quit)root.mainloop

This should do it