如何使用python刷新树视图?

时间:2012-11-27 16:58:10

标签: python pygtk gtktreeview

我是python和gui编程的新手。我正在编写一个程序,它将列出root(/)中的所有目录以及这些目录中的所有子目录。我使用treeview来显示这些目录和子目录为了加速我的程序,我正在使用多线程,但是我遇到的问题是只有在执行了所有线程后才会显示树。我希望在执行任何线程时显示树,并且其他节点动态地附加到树上当其他线程被执行时。谢谢。 这是我的代码

import os
import threading
import gtk

class FileBrowser:      
    def __init__(self):
        self.window = gtk.Window()
        self.window.show_all()
        self.window.connect("destroy", gtk.main_quit)

        box = gtk.VBox()
        box.show()

        self.scrolled_w = gtk.ScrolledWindow()
        self.scrolled_w.show()
        self.window.add(box)

        button = gtk.Button("start")
        button.show()
        button.connect("clicked", self.start_scanning)
        button.set_size_request(30, 50)
        box.pack_start(button, False, False, 4)

        self.model=gtk.TreeStore(str)
        self.treeview = gtk.TreeView(self.model)
        self.treeview.show()

        col = gtk.TreeViewColumn("FileName")
        cell = gtk.CellRendererText()

        self.treeview.append_column(col)
        col.pack_start(cell, 0)
        col.set_attributes(cell, text=0)        

        box.pack_start(self.scrolled_w, 10)
        self.scrolled_w.add(self.treeview)
        self.window.set_size_request(600, 300)

    def start_scanning(self, w):
        self.model.clear()
        main_dir = "/"
        list_dir = os.listdir(main_dir)
        no_of_threads = len(list_dir)
        threads = []

        for i in range(no_of_threads):
            t = threading.Thread(target=self.thread_scanning,
                                 args=(main_dir,list_dir[i],))
            threads.append(t)
            t.start()   
            for t in threads:
                t.join()

    def thread_scanning(self, main_d, list_d):
        path = main_d+""+list_d
        if os.path.isdir(path):
            list_subd = os.listdir(path)
            par = self.model.append(None, [list_d])
            for sub in list_subd:
                self.model.append(par, [sub])

    def main(self):
        gtk.main()


if __name__=="__main__":
    fb = FileBrowser()
    fb.main()

1 个答案:

答案 0 :(得分:0)

因此,您的代码存在两个基本问题。

  1. 正如@windfinder指出的那样,如果您希望线程更新您的gui,则需要运行gobject.threads_init()以使线程与您的gtk应用程序一起正常工作。实际上,如果你不运行gobject.threads_init()

  2. ,它可能会导致许多奇怪的问题
  3. 在您将控制权返回到主循环之前,要求线程加入,直到所有线程都完成后,按钮的回调才会消失。您可以通过gobject添加超时来解决此问题。

  4. 我对你的代码做了一些更改(我还要求线程休眠,这样我就可以看到gui在线程仍在运行时更新了。)

    #!/usr/bin/env python
    
    import gobject
    import time  # This is just used for slowing down the threads
    import os
    import threading
    import gtk
    
    
    class FileBrowser:
    
        def __init__(self):
            self.window = gtk.Window()
            self.window.show_all()
            self.window.connect("destroy", self._destroy)
    
            box = gtk.VBox()
            box.show()
    
            self.scrolled_w = gtk.ScrolledWindow()
            self.scrolled_w.show()
            self.window.add(box)
    
            self.status = gtk.Label("...")  # I added a status label to see when scan is done
            self.status.show()
            box.pack_start(self.status, False, False, 2)
    
            self.button = gtk.Button("start")
            self.button.show()
            self.button.connect("clicked",self.start_scanning)
            self.button.set_size_request(30,50)
            box.pack_start(self.button,False,False,4)
    
            self.model=gtk.TreeStore(str)
            self.treeview = gtk.TreeView(self.model)
            self.treeview.show()
    
            col = gtk.TreeViewColumn("FileName")
            cell = gtk.CellRendererText()
    
            self.treeview.append_column(col)
            col.pack_start(cell,0)
            col.set_attributes(cell,text=0)
    
    
            box.pack_start(self.scrolled_w,10)
            self.scrolled_w.add(self.treeview)
            self.window.set_size_request(600,300)
    
            self.threads = list()  # I made this be part of the full application
            """ That allows us to wait for all threads on close-down, don't know how
            necessary it is."""
    
        def start_scanning(self,w):
    
            self.button.set_sensitive(False)  # To disallow stacking scan-stats
            self.status.set_text("Scanning...")  # Let user know it is started
            self.model.clear()
            main_dir= os.path.expanduser("~")  # I just wanted my home-dir instead
            list_dir = os.listdir(main_dir)
            no_of_threads = len(list_dir)
            for i in range(no_of_threads):
                t = threading.Thread(target=self._thread_scanning,args=(main_dir,list_dir[i],))
                self.threads.append(t)
                t.start()
    
            gobject.timeout_add(200, self._callback)  # This will cause the main app to
            #check every 200 ms if the threads are done.
    
        def _callback(self):
    
            if threading.active_count() == 1:  # If only one left, scanning is done
                self.status.set_text("Done!")
                self.button.set_sensitive(True)  # Allow button being pressed again
                return False  # False make callback stop
    
            print threading.active_count()
            return True
    
        def _thread_scanning(self,main_d,list_d):
            path = os.sep.join((main_d, list_d))  # Made use of os's sep instead...
            if os.path.isdir(path):
                list_subd = os.listdir(path)
                par = self.model.append(None,[list_d])
                for sub in list_subd:
                    self.model.append(par,[sub])
    
            time.sleep(3)  # Useless other than to delay finish of thread.
    
        def main(self):
    
            gtk.main()
    
    
        def _destroy(self, *args, **kwargs):
    
            #Own destroy that waits for all threads...
            for t in self.threads:
                t.join()
    
            gtk.main_quit(*args, **kwargs)
    
    if __name__=="__main__":
        gobject.threads_init()
        fb=FileBrowser()
        fb.main()