2

please help to assign hotkeys to the top entry menu "OPEN".

import tkinter

def fileOpen():
    print('qwerty')

def makeMenu(parent):
    top = tkinter.Menu(parent) 
    parent.config(menu = top)                           

    file = tkinter.Menu(top, tearoff = False)
    file.add_command(label = 'Open...', command = fileOpen, accelerator = 'ctrl+o')
    top.add_cascade(label = 'File', menu = file)

    #top.bind_class(top, '<Control-Key-o>', fileOpen)

root = tkinter.Tk()

makeMenu(root)

root.mainloop()

I need to by pressing "CTRL + O" runs the function "fileOpen"

Sergey
  • 869
  • 2
  • 13
  • 22

1 Answers1

1

You need to:

  1. Bind fileOpen to the root window (root) instead of the menubar (top).

  2. Make fileOpen accept an argument, which will be sent to it when you press Ctrl+o.

Below is a version of your script that addresses these issues:

import tkinter

######################
def fileOpen(event):
######################
    print('qwerty')

def makeMenu(parent):
    top = tkinter.Menu(parent) 
    parent.config(menu = top)                           

    file = tkinter.Menu(top, tearoff = False)
    file.add_command(label = 'Open...', command = fileOpen, accelerator = 'ctrl+o')
    top.add_cascade(label = 'File', menu = file)


root = tkinter.Tk()

############################################
root.bind_all('<Control-Key-o>', fileOpen)
############################################

makeMenu(root)

root.mainloop()

The stuff I changed is in comment boxes.

  • you might want `bind_all` rather than `bind_class`. The former makes the binding work for all windows, the latter makes it only work only when the root window has focus. It's a moot point if you only ever have a single window, but it's important to know the difference. – Bryan Oakley Feb 04 '14 at 17:59