负责打开照片并调整其大小的功能不起作用

时间:2019-04-21 16:20:33

标签: python tkinter

我正在尝试打包负责打开的代码,将图像调整为函数大小,因为我将多次执行此操作。 我有几行显示gui中的图像所需的行:

img = Image.open("images/cola.jpg")
img = img.resize((40, 40), Image.ANTIALIAS)
photoImg = ImageTk.PhotoImage(img)
ColaLabel = ttk.Label(gui, image=photoImg)
ColaLabel.grid(column=6, row=0)
Colala = ttk.Label(gui, text='30')
Colala.grid(column=5, row=0)

GUI如下所示:

enter image description here

我试图通过这种方式制作函数:

def createGUIProduct(path: str):
    img = Image.open(path)
    img = img.resize((40, 40), Image.ANTIALIAS)
    return ImageTk.PhotoImage(img)

并通过这种方式调用它:

ColaLabel = ttk.Label(gui, image=createGUIProduct("images/cola.jpg"))
ColaLabel.grid(column=6, row=0)
Colala = ttk.Label(gui, text='30')
Colala.grid(column=5, row=0)

结果是:

enter image description here

编辑:

修改功能后:

def createGUIProduct(path: str):
    global photoImage
    img = Image.open(path)
    img = img.resize((40, 40), Image.ANTIALIAS)
    photoImage = ImageTk.PhotoImage(img)
    return photoImage

并以相同的方式调用两个产品:

ColaLabel = ttk.Label(gui, image=createGUIProduct("images/cola.jpg"))
ColaLabel.grid(column=6, row=0)
Colala = ttk.Label(gui, text='30')
Colala.grid(column=5, row=0)


WodaLabel = ttk.Label(gui, image=createGUIProduct("images/woda.jpg"))
WodaLabel.grid(column=8, row=0)
Wodala = ttk.Label(gui, text='31')
Wodala.grid(column=7, row=0)

只有一个出现:

enter image description here

1 个答案:

答案 0 :(得分:0)

您使用了不同的函数名称,应该是createGUIImage()而不是createGUIProduct()

更改

ColaLabel = ttk.Label(gui, image=createGUIProduct("images/cola.jpg"))

至:

ColaLabel = ttk.Label(gui, image=createGUIImage("images/cola.jpg"))