Python——tkinker函数中Label图片不显示的问题分析及解决方案

原因:Python的垃圾回收机制错误地“回收”了图片对象,导致图片区域显示为空白

解决办法:在图片变量photo0前面添加global 变量,使之不被回收


在tkinker中插入图片来丰富用户图形界面(GUI),可以通过Label来实现,如在tkinker中插入五个图一中的图标代码如下:

图一

 

import tkinter
from PIL import Image, ImageTk
from tkinter import *
import tkinter.font


def my_tk():
    win = tkinter.Tk()
    win.title("test_image_func")
    win.geometry('300x200')
    win.resizable(False, False)
    photo0 = ImageTk.PhotoImage(file="./pointer.png")
    label0 = Label(win, image=photo0, width=photo0.width(), height=photo0.height())
    label0.place(x=75, y=75)
    label1 = Label(win, image=photo0, width=photo0.width(), height=photo0.height())
    label1.place(x=50, y=50)
    label2 = Label(win, image=photo0, width=photo0.width(), height=photo0.height())
    label2.place(x=100, y=50)
    label3 = Label(win, image=photo0, width=photo0.width(), height=photo0.height())
    label3.place(x=100, y=100)
    label4 = Label(win, image=photo0, width=photo0.width(), height=photo0.height())
    label4.place(x=50, y=100)
    win.mainloop()

if __name__ == '__main__':
    my_tk()

然而,这样的显示是不足以的,有时,我们需要在函数中对tkinker添加图案或图标,而通过如下代码添加的label中的图案却不能显示出来。

import tkinter
from PIL import Image, ImageTk
from tkinter import *
import tkinter.font


def my_tk():
    def add(i, j):
        photo0 = ImageTk.PhotoImage(file="./pointer.png")
        label0 = Label(win, image=photo0, width=photo0.width(), height=photo0.height(), bg="LightBlue")
        label0.place(x=50 * i, y=50 * j)
    win = tkinter.Tk()
    win.title("test_image_func")
    win.geometry('300x200')
    win.resizable(False, False)
    photo = ImageTk.PhotoImage(file="./pointer.png")
    label = Label(win, image=photo, width=photo.width(), height=photo.height())
    label.place(x=75, y=75)
    add(1, 1)
    win.mainloop()

if __name__ == '__main__':
    my_tk()

 

原因:Python的垃圾回收机制错误地“回收”了图片对象,导致图片区域显示为空白

解决办法:在图片变量photo0前面添加global 变量,使之不被回收

上述代码add()函数修改如下:

    def add(i, j):
        global photo0
        photo0 = ImageTk.PhotoImage(file="./pointer.png")
        label0 = Label(win, image=photo0, width=photo0.width(), height=photo0.height(), bg="LightBlue")
        label0.place(x=50 * i, y=50 * j)

 

  • 15
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值