How to dynamically change label text on PyGTK


利用 threading:


首先 initialize threading: gobject.threads.init(), 注意 threading 的结束, 所以最后 gtk.main() 跳出的时候要设定 threading 的属性 quit 为 True

主线程内不可有 block 的行为, 如 while (..), 动态的改变 label text 则是在 MyThread.update_label 实现, 在 MyThread,run() is alive 时候, 调用

gobject.idle_add(self.update_label, output)

 这可使得 label 动态的 perform myfile 的内容.

import pygtk
pygtk.require('2.0')
import gtk
import commands
import time
import gobject
import threading

gobject.threads_init()

class MyThread(threading.Thread):
    def __init__(self, label):
        super(MyThread, self).__init__()
        self.label = label
        self.quit = False
	self.clicked = 0
        self.stop = 0
        self.func = None 

    def update_label(self, counter):
        self.label.set_text(counter)
        return False
 
    def set_clicked(self, clicked):
        self.clicked = clicked
        return False


    def set_func(self, fn):
        self.func = fn  


    def run(self):
        counter = 0
        while not self.quit:
	    if self.clicked:
                counter += 1
                command = '''cat /tmp/myfile '''
                status,output = commands.getstatusoutput(command)
            else:
                output = "no ready..."

            gobject.idle_add(self.update_label, output)
            time.sleep(0.1)

class base:

    def clicked(self, event):
	self.t.clicked = 1	
        
    def __init__(self):
        win=gtk.Window(gtk.WINDOW_TOPLEVEL)
        win.set_size_request(500, 50)
        win.set_title("sample")
        win.show()
        
	win.connect("destroy", lambda _: gtk.main_quit())
        vbox=gtk.VBox(False,0)
        win.add(vbox)
        hbox= gtk.HBox(False,0)
        vbox.add(hbox)

        txt= gtk.Entry()
        txt.set_text("")
        hbox.pack_start(txt,True,True,0)
        
        self.label= gtk.Label()
        vbox.pack_start(self.label,True,True,0)

	self.t = MyThread(self.label)
        self.t.start()

        button= gtk.Button()
        button.set_label("Click me!!")
        # the following passes button and a click event to self.btn
        button.connect("clicked", self.clicked)
        hbox.pack_start(button,True,True,0)
        win.show_all()
        
if __name__=="__main__":
    BASE=base()
    gtk.main()
    BASE.t.quit = True


你可能感兴趣的:(How to dynamically change label text on PyGTK)