2017-10-16 118 views
-1

我正在用tKinter創建一個gui,第一次使用python。 我的gui的一部分是樹形視圖,treeview中的節點附有圖像。 我做了一個功能,添加新的節點到樹形視圖。 我想根據節點的母親將圖像添加到新節點。 在這種情況下,變量'curItem'返回母親作爲字符串,在這種情況下,「測試」。 我想結合字符串「photo_」和「test」並在'tree.insert'代碼中使用它。 但爲了這個工作,我必須將字符串轉換爲別的東西,但我不知道該怎麼做。如何結合兩個字符串來描述tree.insert的屬性?

這可能是一個非常基本的問題,但至今我一直無法找到答案。相關代碼的 部分:

photo_test = PhotoImage(file="resources/test.png") 

def add(): 
    curItem = tree.selection()[0] #returns "test" 
    img = "photo_" + curItem 
    tree.insert(curItem, 'end', text='new', image=img) #doesn't work 
    tree.insert(curItem, 'end', text='new', image=photo_test) #works 

回答

0

你試圖設置圖像的字符串「photo_test」。嘗試將實際的照片存儲在字典中,並通過字符串訪問它,像這樣。

photos = dict() 
photos["photo_test"] = PhotoImage(file="resources/test.png") 

def add(): 
    curItem = tree.selection()[0] #returns "test" 
    img = "photo_" + curItem 
    tree.insert(curItem, 'end', text='new', image=photos[img]) 

你似乎誤解了變量和字符串之間的區別。一個字符串只是代碼中的文本,而不是實際的代碼,所以你不能以字符串形式傳遞一個變量名,並期望代碼讀取該值。 "photo_test"photo_test不一樣。