2017-06-04 58 views
-2

我有一個簡單的GUI試用,我想在屏幕上顯示少量圖像。我開始與設置與灰色方塊印花布它的窗口,並調整所希望的圖像和現在我希望把它在框架上:圖像不能從功能內顯示

img = [img_resize(yellow_square, img_size), "text"] 

base_panel = Label(root, image = img[0]) 
base_txt = Label(root, text = img[1]) 
base_panel.grid(row = x, column = y) 
base_txt.grid (row = x, column = y) 
... 
for im in ls: 
    panel = Label(root, image = im[0]) 
    panel.grid(row = x+im[1][1], column = y+im[1][2])  

    txt = Label(root, text = im[2]) 
    txt.grid(row = x+im[1][1], column = y+im[1][2], sticky = 'S') 

ls是一個列表[圖像(使用Image.open(img)),位置偏移量,文本]

當我複製這些行到我的主腳本,這一切都很好,我得到想要的images

而是試圖從功能做到這一點的時候,我只得到文字部分工作

我猜想我的image = ...有些問題,但我不明白是什麼,因爲我在將這些行復制到main之後工作。主體有另一個圖像,所以這可能會影響到某種程度?

這是代碼主:

for im in background: # background is a list of gray squares 
# some manipulation an a,b 

panel = Label(root, image = im) 
panel.grid(row = a, column = b) 

這裏應該來的函數調用或線本身

回答

1

這是一個常見的問題。你必須保持對圖像的引用,否則python會從內存中刪除它。如果你不在函數中,那麼這個變量是一個全局變量,它保持參考。但是在一個函數中你需要這樣做:

panel = Label(root) 
panel.img = im[0] 
panel.config(image = panel.img) 
+0

字符串不需要相同的句柄?爲什麼? – CIsForCookies

+0

因爲字符串是不可變的。 – Novel

+0

另一件事(無關)。如何在不聲明第一個_global root_的情況下從函數內部安全地使用_root_? – CIsForCookies