Home > Software engineering >  Is there a way to have Tkinter binds work while not focused?
Is there a way to have Tkinter binds work while not focused?

Time:06-21

I'm trying to make a music app, and I want to be able to control things while not focused on the music tab.

window.bind("<Left>", my_function)

works well, but when im in another tab I want that bind to be available still. I want there to be something like:

window.bind("<Left>", myfunction, unfocused=True)

CodePudding user response:

Yes, you can bind to the root window, in which case the binding will fire no matter what widget has the focus. You can bind to the special class of "all" if you want the binding to work even if your app has multiple top-level windows.

If you run the following code, no matter which window or widget has the focus, when you press the F1 key the counter will be updated in the root window.

import tkinter as tk

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

top = tk.Toplevel(root)
top_entry = tk.Entry(top)
top_entry.pack(side="top")

COUNT = 0
def do_f1(event):
    global COUNT
    COUNT  = 1
    label.configure(text=f"You clicked F1 {COUNT} times")

root.bind_class("all", "<F1>", do_f1)

root.mainloop()

Of course, the app itself has to have keyboard focus. There's no way for it to work if you switch to a different application.

CodePudding user response:

You can use system_hotkey to register the keypresses and it will register independently of what window is focused. However the keys that you assign will be inaccessible to other programs while this is running so I sugest adding combinations like alt so that you can still use single keys. Heres an exemple:

from system_hotkey import SystemHotkey

hk = SystemHotkey()
hk.register(['alt', 'q'], callback=start)
hk.register(['alt', 'w'], callback=stop)
  • Related