问题
I wrote a simple PyGTK script to show some basic process information in a TreeView:
import gtk
import os
import pwd
import grp
class ProcParser:
"""
Parses the status file of a particular process
"""
def __init__(self, fname):
self.lines = map(lambda x: x[:-1], open(fname).readlines())
def get_by_val(self, val):
for line in self.lines:
if line.startswith(val):
return line.split()
return []
class Proc:
"""
A process in the /proc filesystem
This class uses a ProcParser to determine it's own information
"""
def __init__(self, pid):
self.pid = int(pid)
self.parser = ProcParser("/proc/{0}/status".format(self.pid))
self._from_file()
def _from_file(self):
self.uid = self.parser.get_by_val("Uid")[1]
self.gid = self.parser.get_by_val("Gid")[1]
self.name = self.parser.get_by_val("Name")[1]
self.user = pwd.getpwuid(int(self.uid)).pw_name
self.group = grp.getgrgid(int(self.gid)).gr_name
class ProcTree:
"A tree that displays all running processes"
def __init__(self):
self.view = gtk.ScrolledWindow()
self.store = gtk.ListStore(str, int, str, str)
self.tree = gtk.TreeView(self.store)
self.cells = [
gtk.CellRendererText(),
gtk.CellRendererText(),
gtk.CellRendererText(),
gtk.CellRendererText()
]
self.tvcols = [
gtk.TreeViewColumn("Name"),
gtk.TreeViewColumn("Pid"),
gtk.TreeViewColumn("User"),
gtk.TreeViewColumn("Group")
]
def __call__(self):
return self.view
def config(self):
for col, cell in zip(self.tvcols, self.cells):
col.pack_start(cell, True)
col.add_attribute(cell, "text", 0)
self.tree.append_column(col)
self._update_store()
self.view.add_with_viewport(self.tree)
def show(self):
self.tree.show()
self.view.show()
def _update_store(self):
self.store.clear()
for item in os.listdir("/proc"):
try: pwid = int(item)
except: continue
pr = Proc(pwid)
self.store.append((pr.name, int(pr.pid), pr.user, pr.group))
class Window:
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.proctree = ProcTree()
def config(self):
self.proctree.config()
self.window.add(self.proctree())
self.window.set_title("Process Viewer")
def show(self):
self.proctree.show()
self.window.show()
def run(self):
self.config()
self.show()
win = Window()
win.run()
gtk.main()
My issue is that all of the columns' values are the same.
Notes:
- Apparently this is correlated with the first column (ie If I change the first column's data, then that's what all of the other data become)
(Will add more as suggestions are posted)
回答1:
for append on treview you should do
rendererText = gtk.CellRendererText()
tvcols = ["Name", "Pid", "User", "Group"]
for num, name in enumerate(tvcols):
column_name = gtk.TreeViewColumn(name ,rendererText, text=num)
self.tree.append_column(column_name)
来源:https://stackoverflow.com/questions/3505171/pygtk-treecolumns-all-exact-duplicates