linux – 无法初始化窗口并等待进程以Python 3 GTK 3结束
我是面向对象编程,Python和GTK 3的新手,尽管我对程序编程(主要是C)有很好的了解.
我正在尝试构建一个简单的Python GTK 3脚本来在Linux下运行pkexec apt-get update. 我有一个mainWindow类(基于Gtk.Window类),它包含一个名为button的按钮对象(基于Gtk.Button类),它触发了一个在单击事件时在mainWindow中定义的new_update_window()方法; new_update_window()方法从updateWindow类(基于Gtk.Window类)初始化updateWindow对象,该类包含名为label的标签对象(基于Gtk.Label类)并调用方法show_all()和update()定义在updateWindow中; update()方法应该更改标签,运行pkexec apt-get update并再次更改标签. 问题是无论我做什么,都会发生以下情况之一: >如果我直接运行subprocess.Popen([“/usr/bin/pkexec”,“/usr/bin/apt-get”,“update”]),则会显示update.Window但是标签会立即设置为值只有在pkexec apt-get update完成执行后才能设置; 文艺青年最爱的 我无法理解如何完成我所追求的目标,即: >显示updateWindow(Gtk.Window) > subprocess.Popen():显示update.Window但是标签立即设置为只有在pkexec apt-get update完成执行后才应设置的值; 这是代码; 不使用线程(案例1,在本例中使用subprocess.Popen()): #!/usr/bin/python3 from gi.repository import Gtk import subprocess class mainWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self,title = "Updater") button = Gtk.Button() button.set_label("Update") button.connect("clicked",self.new_update_window) self.add(button) def new_update_window(self,button): update = updateWindow() update.show_all() update.update() class updateWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self,title = "Updating...") self.label = Gtk.Label() self.label.set_text("Idling...") self.add(self.label) def update(self): self.label.set_text("Updating... Please wait.") subprocess.call(["/usr/bin/pkexec","/usr/bin/apt-get","update"]) self.label.set_text("Updated.") def run_update(self): main = mainWindow() main.connect("delete-event",Gtk.main_quit) main.show_all() Gtk.main() 使用线程(案例3,在本例中使用subprocess.Popen()): #!/usr/bin/python3 from gi.repository import Gtk import threading import subprocess class mainWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self,title = "Updating...") self.label = Gtk.Label() self.label.set_text("Idling...") self.add(self.label) def update(self): self.label.set_text("Updating... Please wait.") thread = threading.Thread(target=self.run_update) thread.start() thread.join() self.label.set_text("Updated.") def run_update(self): subprocess.Popen(["/usr/bin/pkexec","update"]) main = mainWindow() main.connect("delete-event",Gtk.main_quit) main.show_all() Gtk.main() 解决方法
您可以使用
Gio.Subprocess 与GTK的主循环集成,而不是使用Python的子进程模块:
#!/usr/bin/python3 from gi.repository import Gtk,Gio # ... class updateWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self,title="Updating...") self.label = Gtk.Label() self.label.set_text("Idling...") self.add(self.label) def update(self): self.label.set_text("Updating... Please wait.") subprocess = Gio.Subprocess.new(["/usr/bin/pkexec","update"],0) subprocess.wait_check_async(None,self._on_update_finished) def _on_update_finished(self,subprocess,result): subprocess.wait_check_finish(result) self.label.set_text("Updated.") (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |