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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值