How to activate Tkinter menu and toolbar with keyboard shortcut or binding?
You might have seen the menubar and toolbar in the various desktop apps, which are opened through shortcut keys. Don’t you know how to create such a menubar and toolbar which gets opened through a shortcut key? Have a read at the article and get to know the procedure to do the same.
For activating the menubar and toolbar with the shortcut key, create the function for the menubar and toolbar with all the actions you want to perform from the menubar and toolbar respectively. After creating the functions for the menubar as well as a toolbar, write the following code to activate the menubar and toolbar.
app.bind(‘<#Shortcut key to activate menubar>’, #Function for menubar)
app.bind(‘<Shortcut key to activate toolbar>’, #Function for toolbar)
Step 1: First, import the libraries tkinter and ttk.
from tkinter import * from tkinter import ttk
Step 2: Now, create a GUI app using tkinter.
Step 3: Then, set the title and geometry for your app.
app.title(“#Title of the app”) app.geometry('#Dimensions you want to set of an app')
Step 4: Next, declare the function for menubar with event as None such that it works for every case.
Once, you have declared the function, create the menu bar in it.
menubar = Menu()
Inside the function of menubar, declare all the widgets which you want to show in the menubar. Here, we have added the file cascade Menu in the menubar.
file=Menu(menubar, tearoff=False) menubar.add_cascade(label='File', menu=file)
Further, display the menubar in the app.
Step 5: Moreover, declare the toolbar with event as None such that it works for every case.
Once you have created the toolbar function, create and display a label for the toolbar.
toolbar=ttk.Label(app) toolbar.pack(side=TOP, fill=X)
Next, create and display the widgets which you want to show in the toolbar. Here, we have added the button bold_btn in the toolbar.
bold_btn=ttk.Button(toolbar, text="Bold") bold_btn.grid(row=0, column=0, padx=5)
Step 6: Once you have created the function for menu bar as well as toolbar, bind the menu bar as well as toolbar with the shortcut key. Here, we add shortcut key ‘Ctrl+p’ for activating menubar while ‘Ctrl+q’ for activating toolbar.
app.bind('<Control-p>', menubar_shortcut) app.bind('<Control-q>', toolbar_shortcut)
Step 7: Finally, Finally, make the loop for displaying the GUI app on the screen
Below is the full implementation:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course