How to unfocus (blur) Python-gi GTK+3 window on Linux

2024/10/8 2:20:48

What I want to do and why

I want my window to unfocus, so the previous focused window is selected.

Why? I want to interact with the previously selected window (from other programs). My current plan is: unfocus my window, use libxdo to simulate keystrokes, then focus my window again.

My window can be set on top to help avoid flicking. Should be good enough. Looks simple to me. But I can't get it to work.

What I've tried so far

Hiding the window with Gtk.Widget.hide() and then showing it again: The window flickers too much and it's slightly moved some pixels to the top (because of window manager stubbornness, I suppose).

Sample test code

Current code calls Gtk.Window.set_focus(None) that does not work. I need to replace that line with something else that makes what I want it to do.

losefocus.py:

import signal
from gi import require_version
require_version('Gtk', '3.0')
from gi.repository import GLib, Gtk, GObjectclass LoseFocusHandler:def onClick(self, window):print "Losing focus yet?"window1 = builder.get_object("window1")window1.set_focus(None)if __name__ == "__main__":GObject.threads_init()builder = Gtk.Builder()builder.add_from_file("losefocus.glade")builder.connect_signals(LoseFocusHandler())window1 = builder.get_object("window1")window1.show_all()signal.signal(signal.SIGINT, signal.SIG_DFL)Gtk.main()

losefocus.glade:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.16.1 -->
<interface><requires lib="gtk+" version="3.10"/><object class="GtkWindow" id="window1"><property name="can_focus">False</property><property name="window_position">center-always</property><property name="gravity">center</property><child><object class="GtkButton" id="button1"><property name="label" translatable="yes">Lose Focus!</property><property name="visible">True</property><property name="can_focus">True</property><property name="receives_default">True</property><property name="relief">half</property><signal name="clicked" handler="onClick" swapped="no"/></object></child></object>
</interface>
Answer

A simple solution would be to record which window had focus before, both when creating the window and then on each focus-in-event, and explicitly focus that window instead of trying to unfocus the active one:

import signal
from gi import require_version
require_version('Gtk', '3.0')
from gi.repository import GLib, Gdk, Gtk, GObjectclass LoseFocusHandler:def onClick(self, window):print "Losing focus yet?"old_window[0].focus(0)def focus_handler(gdk_window, event):# At this point, our window does not have focus yet, but is# about to. This hence works:old_window[0] = gdk_window.get_screen().get_active_window()if __name__ == "__main__":GObject.threads_init()old_window = [ Gdk.Screen.get_default().get_active_window() ]builder = Gtk.Builder()builder.add_from_file("losefocus.glade")builder.connect_signals(LoseFocusHandler())window1 = builder.get_object("window1")window1.connect("focus-in-event", focus_handler)window1.show_all()signal.signal(signal.SIGINT, signal.SIG_DFL)Gtk.main()
https://en.xdnf.cn/q/70175.html

Related Q&A

SyntaxError: multiple exception types must be parenthesized

I am a beginner and have a problem after installing pycaw for the audio control using python, on putting the basic initialization code for pycaw, i get the following error:- Traceback (most recent call…

Python find difference between file paths

I have a bunch of file paths, such as:path1 = "./base/folder1/subfolder" path2 = "./base/folder2/"I am trying to write a function that can give me the relative difference between th…

Update range of colorbar in matplotlib

I want to update a contourf plot within a function, which works fine. However, the range of the data changes and I therefore also have to update the colorbar. That is where I fail to do so.Please see f…

Anaconda - arrow keys not work well in python shell

I installed Anaconda3 on manjaro (with i3wm and Urxvt). When I go into python interpreter, it is OK to type python script and execute. But when key arrows are pressed to call up history, everything mes…

couldnt remove origin point in matplotlib polycollection

I have tried an example with PolyCollection from matplotlib tutorials and noticed one strange thing. I couldnt remove this points from axes origin see fig. How do I manage this?from mpl_toolkits.mplot…

How to read .odt using Python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 3 years ago.The com…

Modifying Django settings in tests

From Django docs:You shouldn’t alter settings in your applications at runtime. Forexample, don’t do this in a view:from django.conf import settingssettings.DEBUG = True # Dont do this!The only plac…

How To Use Django Cycle Tag

This hopefully is a pretty easy question. My endgoal is to be able to view my database entries in a table which I can sort via the column headers. I have read the documentation on cycle tags, but dont …

Multiple linear regression with python

I would like to calculate multiple linear regression with python. I found this code for simple linear regressionimport numpy as npfrom matplotlib.pyplot import *x = np.array([1, 2, 3, 4, 5])y = np.arra…

How to find source of error in Python Pickle on massive object

Ive taken over somebodys code for a fairly large project. Im trying to save program state, and theres one massive object which stores pretty much all the other objects. Im trying to pickle this object,…