Python。使用 Gtk GUI 在后台做一些工作
- python 3.2.2
- gtk3 3.2.2
- python-gobject 3.0.2
我正在尝试显示 GUI 并在后台执行一些工作。据我了解,它应该看起来像这样:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
from threading import Thread
from gi.repository import Gtk, Gdk
class Gui():
def run(self):
self.Window = Gtk.Window()
self.Window.set_border_width(8)
self.Window.set_title("Некий GUI")
self.Window.connect('destroy', lambda x: self.stop())
self.outBut = Gtk.Button.new_from_stock(Gtk.STOCK_OK)
self.outBut.set_size_request(150, 35)
self.outBut.connect('clicked', lambda x: self.passfun)
self.Window.add(self.outBut)
self.Window.show_all()
def stop(self):
Gtk.main_quit()
def passfun(self):
pass
class LoopSleep(Thread):
def run(self):
i = 1
while True:
print(i)
i = i + 1
#time.sleep(1)
gui = Gui()
gui.run()
loopSleep = LoopSleep()
loopSleep.start()
Gdk.threads_init()
Gdk.threads_enter()
Gtk.main()
Gdk.threads_leave()
但它不起作用。按下按钮时会发生多个循环。并且循环在窗口关闭后运行。但没有在一起。
我做错了什么?
- python 3.2.2
- gtk3 3.2.2
- python-gobject 3.0.2
I'm trying to display a GUI and do some work in the background. As I understand it should look something like this:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
from threading import Thread
from gi.repository import Gtk, Gdk
class Gui():
def run(self):
self.Window = Gtk.Window()
self.Window.set_border_width(8)
self.Window.set_title("Некий GUI")
self.Window.connect('destroy', lambda x: self.stop())
self.outBut = Gtk.Button.new_from_stock(Gtk.STOCK_OK)
self.outBut.set_size_request(150, 35)
self.outBut.connect('clicked', lambda x: self.passfun)
self.Window.add(self.outBut)
self.Window.show_all()
def stop(self):
Gtk.main_quit()
def passfun(self):
pass
class LoopSleep(Thread):
def run(self):
i = 1
while True:
print(i)
i = i + 1
#time.sleep(1)
gui = Gui()
gui.run()
loopSleep = LoopSleep()
loopSleep.start()
Gdk.threads_init()
Gdk.threads_enter()
Gtk.main()
Gdk.threads_leave()
But it does not work. Several cycles occurs when you press the button. And the cycle runs after the window is closed. But not together.
What I do wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不能声称自己是 python 线程或 gtk3 方面的专家,但在玩了一下你的示例后,我发现一些东西似乎可以按照你想要的方式工作。我使用 threading.start(target=loop_sleep) 代替子类 Thread,并将其放置在 Gui 内。
Glib.threads_init() 似乎也需要。
Can't claim to be any expert on python threading nor gtk3 but after playing around a little with your example I found something that appears to work the way you want it. Instead of sub classing Thread i use threading.start(target=loop_sleep), and placed that inside Gui.
Glib.threads_init() also seem to be needed.