2017-06-04 61 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