Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle, when tkinter window gets focus

I have this code:

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

It prints hello world only once, and then it stops working. No more hello world Basically WM_TAKE_FOCUS does not work.

like image 566
Jakub Bláha Avatar asked Jun 18 '17 08:06

Jakub Bláha


People also ask

What does focus () do in tkinter?

Focus is used to refer to the widget or window which is currently accepting input. Widgets can be used to restrict the use of mouse movement, grab focus, and keystrokes out of the bounds. However, if we want to focus a widget so that it gets activated for input, then we can use focus. set() method.

How can I tell if tkinter Mainloop is running?

If you know the process name, in Windows, you can use psutil to check if a process is running. if __name__ == "__main__": app_name = 'chrome' if is_running(name=app_name): if kill(name=app_name): print(f'{app_name} killed! ') else: print(f'{app_name} is not running!

What is the purpose of the focus method in a tkinter widget Python?

It focuses the widget and makes them active until the termination of the program.


2 Answers

You can bind a function to the <FocusIn> event. 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'll need to compare event.widget to 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()
like image 114
Bryan Oakley Avatar answered Sep 25 '22 16:09

Bryan Oakley


"Note that WM_SAVE_YOURSELF is deprecated, and Tk apps can't implement WM_TAKE_FOCUS or _NET_WM_PING correctly, so WM_DELETE_WINDOW is the only one that should be used". Here's a link! If you need to keep tkinter focus all the time:

w.wm_attributes("-topmost", 1)

does a pretty good job.

like image 42
Bimal Paudel Avatar answered Sep 23 '22 16:09

Bimal Paudel