0

我正在 Tkinter 中制作程序 GUI,但我被困在这部分。

from Tkinter import *
from PIL import Image, ImageTk

def add_imgage():
    player_label.destroy()
    player3_token = ImageTk.PhotoImage(Image.open('./gallery/Scissor_icon.jpg'))
    player_label = Label(vs_frame, image=player3_token, borderwidth=2, relief=GROOVE, width=50, height=50)

if __name__ == '__main__':
    root = Tk()

    SCREEN_HEIGHT = 500
    SCREEN_WIDTH = 800
    root.geometry(f"{SCREEN_WIDTH}x{SCREEN_HEIGHT}")
    root.title('test window')
    
    frame1 = Frame(root)
    frame1.pack(pady=30)

    player_label = Label(frame1, borderwidth=2, relief=GROOVE, width=10, height=5)
    player_label.pack(side=LEFT)

我想player_label通过add_image()函数添加图像。

4

1 回答 1

1

第一的; 您必须运行该功能才能创建图像。

然后; 无需销毁标签。您可以就地配置它。您还必须保存对图像的引用,否则当函数退出时它将被垃圾收集。

我正在使用 Python3,所以我将名称更改Tkintertkinter,没有第一个大写字母。

from tkinter import *
from PIL import Image, ImageTk

def add_imgage():
    player3_token = ImageTk.PhotoImage(Image.open('images/jones.png'))
    player_label.config(image=player3_token, borderwidth=2, # Config the label
                         relief=GROOVE, width=50, height=50)
    player_label.image = player3_token  # Save reference to image

if __name__ == '__main__':
    root = Tk()

    SCREEN_HEIGHT = 500
    SCREEN_WIDTH = 800
    root.geometry(f"{SCREEN_WIDTH}x{SCREEN_HEIGHT}")
    root.title('test window')
    
    frame1 = Frame(root)
    frame1.pack(pady=30)

    player_label = Label(frame1, borderwidth=2, relief=GROOVE,
                         width=10, height=5)
    player_label.pack(side=LEFT)

    add_imgage()    # Run the function to add image
于 2020-11-24T06:58:52.117 回答