2
我正在製作一個基本的文件管理器,並在我的帖子標題中卡住了問題。 首先它在目錄中查找,生成項目列表,並將它們附加到樹視圖列表中。Python GtkTreeview;如何在選擇項目時刷新列表
如果單擊一個子目錄,它將成爲新的當前目錄。我所需要的就是將其發回到def,它讀取並顯示當前目錄的內容(我認爲)。
import gtk, os
class PyApp(gtk.Window):
def __init__(self):
super(PyApp, self).__init__()
self.set_size_request(250, 200)
self.set_position(gtk.WIN_POS_CENTER)
self.connect("destroy", gtk.main_quit)
self.set_title("SteveFM")
vbox = gtk.VBox(False, 8)
sw = gtk.ScrolledWindow()
sw.set_shadow_type(gtk.SHADOW_ETCHED_IN)
sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
vbox.pack_start(sw, True, True, 0)
store = self.create_model()
treeView = gtk.TreeView(store)
treeView.connect("row-activated", self.on_activated)
treeView.set_rules_hint(True)
sw.add(treeView)
self.create_columns(treeView)
self.add(vbox)
self.show_all()
# Take the names of files and subdirectories in
# the current directory and sort them into a list for treeview
def create_model(self):
store = gtk.ListStore(str)
dirList=os.listdir(os.getcwd())
dircontents = []
for item in dirList:
if item[0] != '.':
if os.path.isdir(item):
dircontents.append(['/'+item])
else:
dircontents.append([item])
dircontents.sort()
for act in dircontents:
store.append([act[0]])
return store
# If a file is clicked, open with leafpad.
# If a directory is clicked, change the current working directory to it
# and (my hurdle) replace the current treeview list with the contents of the
# new directory, just like a file manager.
def on_activated(self, widget, row, col):
model = widget.get_model()
target = model[row][0]
if target[0] != "/":
cmd = "leafpad "+target
os.system(cmd)
else:
os.chdir(os.getcwd()+target)
print os.getcwd() # Just for debugging
def create_columns(self, treeView):
rendererText = gtk.CellRendererText()
column = gtk.TreeViewColumn(None, rendererText, text=0)
column.set_sort_column_id(0)
treeView.append_column(column)
PyApp()
gtk.main()
驚人,感謝傑里米。 –
您不需要創建新模型,但需要更新正在使用的模型,然後GtkTreeView將自行更新視圖。 – erick2red
@ erick2red 我讀過你的建議是正確的方法,但卻對如何做到這一點感到困惑。也許傑裏米改變了「自我」。在init中將允許我再次解決這個問題。 –