9

Is there some event triggering when tkinter window loses focus that can be bound to a tkinter window using the .bind method?

Jakub Bláha
  • 1,491
  • 5
  • 22
  • 43
  • 2
    Possible duplicate of [Tk/Tkinter: Detect application lost focus](https://stackoverflow.com/questions/18089068/tk-tkinter-detect-application-lost-focus) – Dmitry Oct 04 '17 at 14:31
  • 1
    See [Event types](https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/event-types.html) (since @j_4321's link no longer works). – martineau Jul 01 '21 at 15:13

1 Answers1

21

The event you are looking for is <FocusOut>.

import tkinter as tk

def on_focus_out(event):
    if event.widget == root:
        label.configure(text="I DON'T have focus")

def on_focus_in(event):
    if event.widget == root:
        label.configure(text="I have focus")

root = tk.Tk()
label = tk.Label(width=30)
label.pack(side="top", fill="both", expand=True)

root.bind("<FocusIn>", on_focus_in)
root.bind("<FocusOut>", on_focus_out)

root.mainloop()
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • 1
    I am using `window.overrideredirect(True)` and with this it does not work. – Jakub Bláha Oct 06 '17 at 13:20
  • 1
    @JakubBláha: you need to add that detail to your question. – Bryan Oakley Oct 06 '17 at 14:30
  • Althought Bryan Oakley is right, you need to mention such details, it still works perfectly for me. I don't know if it's dependend on the OS (thats also an information missing in your question though) but it works well on Windows 10 Home (Python 3.7, Tcl/Tk 8.5). – Nummer_42O May 24 '20 at 13:14
  • Is it possible for tkinter window to never have focus but still be able to click buttons staying on top? Like on screen keyboard? – Delrius Euphoria Apr 02 '21 at 08:38