'Binding a key to a tkinter window, with exception of the entry field

Picture of my GUI for clarity

I made a tool that plays audio from youtube. I want it to pause when the spacebar is pressed. I do this by this piece of code:

win.bind('<space>',lambda event:funcPP(player, btnPP))

win is my window, funcPP is the play/pause function.

My problem is that I have also an Entry in my window (for searching videos) and of course it is impractical if the video pauses everytime when I search a new video and press Spacebar. And the real problem is that, once I have clicked the Entry field, the focus stays there. It doesn't go away after clicking somewhere else! This sabotages my Spacebar shortcut.

Any tips how I can solve this?



Solution 1:[1]

I found the solution.

With:

win.bind_all("<Button-1>", lambda event: event.widget.focus_set())

It is possible to put the focus whereever one clicks.

then:

win.bind('<space>',lambda event:funcPPTRANSFER(player))

To bind spacebar to the whole window

then:

def funcPPTRANSFER(player):
    if str(win.focus_get()) != str(".!entry"):
        funcPP(player)

Have the function check whether the spacebar was sent from the entry or from somwhere else in the window

EDIT: Another thing I found now: https://stackoverflow.com/a/56519799/18664063

if isinstance(event.widget,tk.Tk): #check if event widget is Tk root window

very nice function that might help as well in this project.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1