pythontkintermenubaraccelerator

Accelerators not working in Python Tkinter : How to fix


I am adding accelerators to a button in the TOPLEVEL menu bar in tkinter for a to a project in python I have been working on lately, and after doing some research, I found a site explaining how to accomplish this. Unfortunately, this does not activate the function.

I've been wondering if maybe this is because it binds to the button, instead of the function itself.

class Window:

    def init_window(self):

        menu = Menu(self.master)

        self.master.config(menu=menu)

        file = Menu(menu)

        file.add_command(label="Exit", command=self.client_exit, accelerator="Ctrl+Q")

        file.add_command(label="Save", command=self.save_file, accelerator="Ctrl+S")

        file.add_command(label="Open...", command=self.open_file, accelerator="Ctrl+O")

        menu.add_cascade(label="File", menu=file)

        edit = Menu(menu)

        edit.add_command(label="Undo", accelerator="Ctrl+Z")

        edit.add_command(label="Redo", accelerator="Ctrl+Shift+Z")

        menu.add_cascade(label="Edit", menu=edit)

        view = Menu(menu)

        view.add_command(label="Change Colors...", accelerator="Ctrl+Shift+C")

        menu.add_cascade(label="View", menu=view)

Unfortunately, the accelerator doesn't activate. I'm new to Python, so sorry if this question is easy.


Solution

  • You have to use bind_all.

    Accelerator is just a string that will shown on the right of the menu

    Underline - to underline the selected index

    tearoff - boolean to toggle the tear off feature

    tearoff allows you to detach menus for the main window creating floating menus. If you create a menu you will see dotted lines at the top when you click a top menu item. If you click those dotted lines the menu tears off and becomes floating.

    from tkinter import *
    
    def donothing(event=None):
       filewin = Toplevel(root)
       button = Button(filewin, text="Cool")
       button.pack()
    
    root = Tk()
    menubar = Menu(root)
    
    helpmenu = Menu(menubar, tearoff=0)
    helpmenu.add_command(label="Help Index",accelerator="Ctrl+H", command=donothing)
    menubar.add_cascade(label="Help",underline=0 ,menu=helpmenu)
    root.config(menu=menubar)
    root.bind_all("<Control-h>", donothing)
    root.mainloop()