How to handle when a tkinter window gets focus

I have this code:

from tkinter import *
w = Tk()
w.protocol('WM_TAKE_FOCUS', print('hello world'))
mainloop()

      

It hello world

only prints once and then it stops working. More hello world

in principle WM_TAKE_FOCUS

does not work.

+3


source to share


2 answers


You can bind a function to an event <FocusIn>

. When you bind to the root window, the binding is applied to every widget in the root window, so if you only want to do something when the window as a whole gets focus, you need to compare event.widget

against the root window.

For example:



import Tkinter as tk

def handle_focus(event):
    if event.widget == root:
        print("I have gained the focus")

root = tk.Tk()
entry1 = tk.Entry(root)
entry2 = tk.Entry(root)

entry1.pack()
entry2.pack()

root.bind("<FocusIn>", handle_focus)

root.mainloop()

      

+5


source


"Please note that WM_SAVE_YOURSELF is deprecated and Tk applications cannot properly implement WM_TAKE_FOCUS or _NET_WM_PING, so WM_DELETE_WINDOW is the only one that should be used." Here's the link ! If you need to keep tkinter focus all the time:

w.wm_attributes("-topmost", 1)

      



does a pretty good job.

0


source







All Articles