i am new to PyGtk. i don't know how to get realtime update on gtk.
such as downloadmanagers show's every time the speed changes.

here is my. in this code the "f='/home/tree.txt'" is a log file .this file regularly updated by another thread. i want to add the file contents to TreeView with regular update. is it need any loop, if yes where i can loop?

import codecs,gtk

def redraw():
	f='/home/tree.txt'  #this is realtime log file
	log=codecs.open(f,'r','utf-8')
	d=log.read()
	log.close
	return d


DATA = [
	[0, redraw()],
	[1, "one"],
	[2, "two"],
	[3, "three"],
	[4, "four"],
	[5, "five"],
	[6, "six"],
	[7, "seven"],
	[8, "eight"],
	]

class t_treeview_sort(gtk.Window):
	def __init__(self):
		gtk.Window.__init__(self)

		self.set_title("Treeview")
		self.set_geometry_hints(min_width=200)
		self.connect("destroy", gtk.main_quit)

		self.list = gtk.ListStore(int, str)
		self.sort_order = gtk.SORT_ASCENDING
		while gtk.events_pending():
			gtk.main_iteration()
		for data in DATA:
			iter = self.list.append( data )
			self.list.set(iter)

		self.treeview = gtk.TreeView()
		model = self.treeview.get_selection()
		model.set_mode(gtk.SELECTION_SINGLE)
		r = gtk.CellRendererText()

		tc = gtk.TreeViewColumn("Id", r, text=0)
		self.treeview.insert_column(tc, -1)

		tc = gtk.TreeViewColumn("Text", r, text=1)
		self.treeview.insert_column(tc, -1)

		self.treeview.set_model(self.list)
		self.treeview.set_headers_clickable(True)
		

		self.treeview.show()
		self.add(self.treeview)

t = t_treeview_sort()
t.show()
gtk.main()

Thanks in advance.

Dani AI

Generated

wanted the TreeView to follow a log file in real time; suggested a watcher thread and signaling. Both approaches are valid, but the simplest and safest way with PyGTK is to keep GTK calls on the main thread. Two practical patterns work well: (A) poll the file from the GTK main loop with a timer, or (B) run a background watcher and marshal updates back into the main loop with gobject.idle_add. Avoid manual calls to gtk.main_iteration() or calling GTK APIs directly from worker threads.

A compact polling example that runs in the GTK main thread (works for PyGTK / GTK2):

import gtk
import gobject

class LiveTree:
    def __init__(self, logfile, interval_ms=1000):
        self.logfile = logfile
        self.store = gtk.ListStore(int, str)
        self._prev = []
        gobject.timeout_add(interval_ms, self._poll)

    def _poll(self):
        try:
            with open(self.logfile, 'r') as f:
                lines = [l.rstrip('\n') for l in f]
        except IOError:
            return True
        if lines != self._prev:
            self._prev = lines
            self.store.clear()
            for i, line in enumerate(lines):
                self.store.append([i, line])
        return True

If you prefer a background watcher (useful for heavy checks or when using inotify), have the thread only notify the GUI via gobject.idle_add so the actual ListStore modifications run on the main loop:

import threading, time, os, gobject

def _watch(path, notify):
    last = 0
    while True:
        try:
            m = os.path.getmtime(path)
        except OSError:
            m = 0
        if m != last:
            last = m
            gobject.idle_add(notify)
        time.sleep(0.5)

t = threading.Thread(target=_watch, args=(filename, my_update))
t.setDaemon(True)
t.start()

Quick troubleshooting notes: use with or call close() so files are closed; remove any stray self.list.set(iter) calls (append already inserts the row); pick a sensible poll interval (250ms–2000ms) to balance responsiveness and CPU. If updates are frequent or you need efficiency, use an OS watcher (inotify on Linux or a cross-platform library) but still marshal updates back with gobject.idle_add.

I'd have a separate thread that looks for changes to the file. When it sees a change the thread should send a signal. You can then have your treeview listen for that signal and call a handler to update what's displayed. See for more info on creating your own signals.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.