我找到了一個函式,它回傳一個帶有給定檔案路徑的位圖圖示。除此之外,我還有一個函式可以在給定目錄中創建一個包含檔案和檔案夾的樹。我希望我的樹顯示目錄名稱及其圖示,但它只顯示名稱。我采用了面向物件的編碼方法。
def populate(self, path):
if os.path.isdir(path):
with os.scandir(path) as it:
for entry in it:
if not entry.name.startswith('.') and entry.is_dir():
values1 = [time.asctime(time.localtime(os.path.getmtime(entry.path))), "Folder",
os.path.getsize(entry.path)]
self.tree.insert("", 'end', text=entry.name, values=values1, open=False, image=self.folderimg)
if not entry.name.startswith('.') and entry.is_file():
icon_id = iconHelper.get_icon(path=entry.path, size="small")
icon = ImageTk.PhotoImage(icon_id)
values2 = [time.asctime(time.localtime(os.path.getmtime(entry.path))), "File",
os.path.getsize(entry.path)]
self.tree.insert("", 'end', text=entry.name, values=values2, open=False, image=icon)
else:
try:
os.startfile(path)
except OSError:
print("File can not be opened")
“填充”函式在一個類中。我知道icon變數的范圍是本地的。我嘗試了一種self.icon方法,但它不起作用
我怎樣才能使每個“圖示”變數的范圍對類全域化?
uj5u.com熱心網友回復:
您可以簡單地使用型別的實體變數list來存盤這些圖示影像:
def populate(self, path):
if os.path.isdir(path):
self.icons = [] # instance variable to store those icon images
with os.scandir(path) as it:
for entry in it:
if not entry.name.startswith('.') and entry.is_dir():
values1 = [time.asctime(time.localtime(os.path.getmtime(entry.path))), "Folder",
os.path.getsize(entry.path)]
self.tree.insert("", 'end', text=entry.name, values=values1, open=False, image=self.folderimg)
if not entry.name.startswith('.') and entry.is_file():
icon_id = iconHelper.get_icon(path=entry.path, size="small")
icon = ImageTk.PhotoImage(icon_id)
values2 = [time.asctime(time.localtime(os.path.getmtime(entry.path))), "File",
os.path.getsize(entry.path)]
self.tree.insert("", 'end', text=entry.name, values=values2, open=False, image=icon)
self.icons.append(icon) # save the reference of the icon image
else:
try:
os.startfile(path)
except OSError:
print("File can not be opened")
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/345019.html
