我是 Python 和 GUI 编程的新手。我试图通过做一个小应用程序来学习两者。在我的应用程序中,后台进程应该始终运行并通过 appindicator 显示用户的一些虚构配额。这是我的代码:
#!/usr/bin/env python
import pyjsonrpc
from gi.repository import Gtk
from gi.repository import AppIndicator3 as appindicator
import thread
import glib
ind = None
def start_gtk_main():
ind = appindicator.Indicator.new(
"example-simple-client",
"indicator-messages",
appindicator.IndicatorCategory.APPLICATION_STATUS)
ind.set_status (appindicator.IndicatorStatus.ACTIVE)
ind.set_label('NA', '')
menu = Gtk.Menu()
menu_quit = Gtk.MenuItem("Quit")
menu_quit.connect("activate", quit_app)
menu.append(menu_quit)
menu_quit.show()
ind.set_menu(menu)
try:
thread.start_new_thread(update_ind_label, ())
except:
print "Error: unable to start thread"
Gtk.main()
def quit_app(self):
Gtk.main_quit()
def update_ind_label():
value = glib.timeout_add_seconds(5, handler_timeout)
def handler_timeout():
url = "http://localhost/jsonrpc-server/"
http_client = pyjsonrpc.HttpClient(url)
response = http_client.call("getQuota", 2)
quota = response.get('quota')
ind.set_label(quota+'%', '')
return True
if ind is None:
start_gtk_main()
Run Code Online (Sandbox Code Playgroud)
问题是每当 glib 的 timeout_add_seconds 触发回调函数 handler_timeout 时,它都会给我分段错误错误。
我也试过没有线程,如:
# ....other code....
glib.timeout_add_seconds(5, handler_timeout)
Gtk.main()
# ....other code....
Run Code Online (Sandbox Code Playgroud)
但它给了我同样的错误。
我在 Internet 上看到了许多类似的问题,其中大多数建议使用 GLib 或 GObject 的超时函数或线程,但在我的情况下没有一个工作。谁能告诉我我在这里做错了什么?
仅供参考,我的操作系统是 Xubuntu 13.10。
代替:
import glib
Run Code Online (Sandbox Code Playgroud)
和:
from gi.repository import GLib as glib
Run Code Online (Sandbox Code Playgroud)
和代码应工作,虽然你需要一个global ind之初 start_gtk_main(),否则ind将创建本地的功能,你会得到一个异常handler_timeout()即ind是None。