Sergey
Sergey

Reputation: 1001

how to assign hotkeys?

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"

Upvotes: 2

Views: 2747

Answers (1)

user2555451
user2555451

Reputation:

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.

Upvotes: 1

Related Questions