【问题标题】:Python. Doing some work on background with Gtk GUIPython。使用 Gtk GUI 在后台做一些工作
【发布时间】:2011-12-28 13:59:54
【问题描述】:
  • 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()

但它不起作用。当您按下按钮时会发生几个循环。并且在窗口关闭后循环运行。但不是在一起。

我做错了什么?

【问题讨论】:

  • 您应该在问题中包含代码。
  • 我用的是pastebin,因为我看不懂这里的代码是怎么粘贴的。
  • 你把它粘贴进去,选择它,然后在编辑器中按下代码按钮。
  • 不,不需要任何偏差而已:

标签: python gtk python-3.x pygobject gtk3


【解决方案1】:

不能声称自己是 python 线程或 gtk3 方面的专家,但在对您的示例进行了一些尝试之后,我发现某些东西似乎可以按照您想要的方式工作。我使用 threading.start(target=loop_sleep) 而不是子类化 Thread,并将其放在 Gui 中。

似乎也需要 Glib.threads_init()。

#!/usr/bin/env python3
from gi.repository import Gtk,Gdk, GLib
import threading 
import time

class Gui(Gtk.Window):
  def __init__(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.Window.connect('destroy', lambda x: self.stop())
      self.Window.add(self.outBut)

      self.Window.show_all()
      threading.Thread(target=loop_sleep).start()

  def stop(self):
      Gtk.main_quit()

  def passfun(self):
      pass

def loop_sleep():
      i = 1
      while True:
           print(i)
           i = i + 1
           #time.sleep(1)



app = Gui()
GLib.threads_init()
Gdk.threads_init()
Gdk.threads_enter()
Gtk.main()
Gdk.threads_leave()

【讨论】:

    猜你喜欢
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 2020-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    相关资源
    最近更新 更多