如何在Linux上解散(模糊)Python-gi GTK + 3窗口

时间:2016-03-16 07:53:29

标签: python python-2.7 ubuntu x11 gtk3

我想做什么以及为什么

我希望我的窗口不聚焦,因此选择了先前的聚焦窗口。

为什么呢?我想与之前选择的窗口(来自其他程序)进行交互。我目前的计划是:取消我的窗口,使用libxdo来模拟击键,然后再次对焦我的窗口。

我的窗口可以设置在顶部以帮助避免轻弹。应该够好了。看起来很简单。但我无法让它发挥作用。

到目前为止我尝试了什么

Gtk.Widget.hide()隐藏窗口,然后再次显示:窗口闪烁太多,稍微移动了一些像素到顶部(因为窗口管理器固执,我猜)。

示例测试代码

当前代码调用Gtk.Window.set_focus(None)不起作用。我需要用其他东西替换那条线,这些东西能让我想做它。

losefocus.py

import signal
from gi import require_version
require_version('Gtk', '3.0')
from gi.repository import GLib, Gtk, GObject

class 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>

1 个答案:

答案 0 :(得分:1)

一个简单的解决方案是记录哪个窗口之前有焦点,无论是在创建窗口时还是在每个focus-in-event上,并明确地关注该窗口而不是尝试取消聚焦活动窗口:

import signal
from gi import require_version
require_version('Gtk', '3.0')
from gi.repository import GLib, Gdk, Gtk, GObject

class 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()