在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)