Quentin
Quentin

Reputation: 17

How to detect if my Tkinter windows has focus?

I'm making a tkinter app and I need to know if my windows had focus, because I will send notifications only if the windows don't have focus. I check the root protocols but I didn't find something suitable.

Upvotes: 1

Views: 2625

Answers (3)

Thimo1
Thimo1

Reputation: 119

This question has already been answered, but the accepted answer is more complicated than it should be.

I think the cleanest solution to this problem would be the following:

def has_focus(window):
        return window.focus_displayof()    # returns None if the window does not have focus

if not has_focus(root):
    # do something

Upvotes: 4

Saad
Saad

Reputation: 3430

There can be several methods of doing this depending upon how you what the function to trigger.

Let's say you want the notification to go when the window loses focus then with the help of <FocusOut> bind we can do so

...

def send_notification(*args):
    """triggers when the window loses focus."""
    ...

root = tk.Tk()
root.bind('<FocusOut>', send_notification)
...

Or Let us the notification function trigger different times even if the window has focus or not then we can check in the function like so

def send_notification(*args):
    """triggers when the window loses focus."""
    if not focus_check.get():
        ...

root = tk.Tk()

focus_check = tk.BooleanVar()
root.bind('<FocusIn>', lambda _: focus_check.set(True))
root.bind('<FocusOut>', lambda _: focus_check.set(False))

Upvotes: 1

solarmainframe
solarmainframe

Reputation: 25

I found a StackOverflow question that seems fairly similar to yours. In essence, you need to add a binding to your Tkinter application. This will only function if your application has focus. You can also use the focus_get command to figure out if your obejct has focus if you apply it to the root object.

Here's the code the answer from 2009 used: e1.bind("<Return>", handleReturn)

Upvotes: 0

Related Questions