aitsuri
aitsuri

Reputation: 33

Python 3 tkinter keyboard shortcuts call a function

I have a function that I'm trying to call by pressing two key on the keyboard. Example : Ctrl+N

self._first_event = None
self._second_event = None

def function(self, event):
    if self._first_event == None:
        self._first_event = event
    else:
        self._second_event = event
        if self._first_event == 'Ctrl' and self._second_event == 'n':
            return someotherfunction()

I tried this code but it doesn't call the someotherfunction()

Upvotes: 1

Views: 1722

Answers (1)

codingfish
codingfish

Reputation: 400

This code is doing what you are trying to achieve:

from tkinter import *

def someotherfunction(e=None):
    print('It works !')

root = Tk()
root.bind('<Control-n>', someotherfunction)
root.mainloop()

I think it's a more proper way to to do it than how you were trying to do it. By the way if you look at the documentation of the event object it contains multiple things so you can't compare it to a string like so. You should use event.keysym for exemple.

Note:

<a> correspond to A

<A> correspond to Shift+A

<Control-n> correspond to Ctrl+N

<Control-N> correspond to Ctrl+Shift+N

Upvotes: 1

Related Questions