GTK主要块 - Python

bel*_*ace 0 python gtk event-loop

我是GTK的新手,我偶然发现了一个听起来简单的问题,但我找不到解决问题的方法.基本上,调用gtk.main()使我的单线程进程停止.我知道这gtk.main()是阻塞的,但我之前没有打过电话gtk.main(),所以退出主循环不会有任何好处,因为没有循环退出.

即便如此,gtk.main_level()返回0.此外,当我gtk.main()从python命令行尝试时,它也会挂起.我缺少一些基本的东西,有人能指出这个吗?赞赏.

编辑:我需要的Gtk方法是gobject.add_timeout这样的:

gobject.timeout_add(2000, callback)
gtk.main() # This blocks the thread.
Run Code Online (Sandbox Code Playgroud)

gpo*_*poo 8

看起来它正在阻止应用程序,但正在做的是处理事件.其中一个事件必须终止循环.您可以查看维基百科中事件循环背后的想法.

如果你不想编程图形界面,那么你不需要Gtk,你只需要Glib.这里有一个示例向您展示主循环如何工作(概念在Gtk和Glib中类似):

from gi.repository import GLib, GObject

counter = 0

def callback(*args):
    global counter
    counter += 1
    print 'callback called', counter
    if counter > 10:
        print 'last call'
        return False

    return True

def terminate(*args):
    print 'Bye bye'
    loop.quit()

GObject.timeout_add(100, callback)
GObject.timeout_add(3000, terminate)
loop = GLib.MainLoop()
loop.run()
Run Code Online (Sandbox Code Playgroud)

如果回调返回False,那么它将被删除而不再被调用.如果你想再次调用回调,它必须返回True(正如你在函数中看到的那样callback).

我设置了另一个回调terminate来显示如何退出循环.如果你没有明确地做,那么GLib将继续等待更多事件(它没有任何方法可以知道你想做什么).

使用PyGTK(旧的和不推荐的),代码将是:

import gobject, glib, gtk

counter = 0

def callback(*args):
    global counter
    counter += 1
    print 'callback called', counter
    if counter > 10:
        print 'last call'
        return False

    return True

def terminate(*args):
    print 'Bye bye'
    loop.quit()

gobject.timeout_add(100, callback)
gobject.timeout_add(3000, terminate)
loop = glib.MainLoop()
loop.run()
Run Code Online (Sandbox Code Playgroud)