tkinter图片插入PIL问题

为什么点击运行后页面一和页面五的两张照片一块出来了

img

然后运行到第五个页面的时候,又没有照片了

img

第一个页面代码:


image1 = Image.open(r"C://Users//29212//Desktop//mbti1.jpg")
zoom = 1.8
pixels_x1, pixels_y1 = tuple([int(zoom * x) for x in image1.size])
img1 = ImageTk.PhotoImage(image1.resize((600, 400)))
label1 = Label(root, image=img1)
label1.image = img1
label1.pack()

第五个页面代码:

fifth = tk.Toplevel()

def f():
    fifth = Toplevel()
    fourth.update()
    fifth.update()
    fourth.destroy()
    fifth = Toplevel()
    fifth.geometry("800x800")
    fifth.title("最终结果")
    fifth.configure(bg="AntiqueWhite")

btn6 = Button(fourth, text="最终结果显示", width=8, command=f)
btn6.place(x=600, y=280)

image2 = Image.open(r"C:\Users\29212\Desktop\results.jpg")
zoom = 1.8
pixels_x2, pixels_y2 = tuple([int(zoom * x) for x in image2.size])
img2 = ImageTk.PhotoImage(image2.resize((600, 400)))
label2 = Label(fifth, image=img2)
label2.image = img2
label2.pack()

image3 = Image.open(r"C:\Users\29212\Desktop\results2.jpg")
zoom = 1.8
pixels_x3, pixels_y3 = tuple([int(zoom * x) for x in image3.size])
img3 = ImageTk.PhotoImage(image3.resize((600, 400)))
label3 = Label(fifth, image=img3)
label3.image = img3
label3.pack()

请各位帮帮忙,刚转专业,不太懂

【以下回答由 GPT 生成】

问题产生的原因是在第五个页面的代码中,定义了一个名为f()的函数,并在其中创建了一个新的Toplevel窗口fifth,并将其赋值给了函数内的fifth变量。接着又在该函数内销毁了之前的fourth窗口,并重新创建了一个新的fifth窗口。由于之前已经创建的label2和label3控件是依附于之前的fifth窗口的,而且在重新创建的fifth窗口中没有重新创建这两个控件,所以导致第五个页面中没有显示图片。

要解决这个问题,可以在f函数内先销毁之前创建的label2和label3控件,然后再创建新的label2和label3控件,并把它们绑定到新创建的fifth窗口上。

以下是修改后的代码:

fifth = tk.Toplevel()

def f():
    fifth.update()
    fifth.destroy()
    fifth = Toplevel()
    fifth.geometry("800x800")
    fifth.title("最终结果")
    fifth.configure(bg="AntiqueWhite")

    image2 = Image.open(r"C:\Users\29212\Desktop\results.jpg")
    zoom = 1.8
    pixels_x2, pixels_y2 = tuple([int(zoom * x) for x in image2.size])
    img2 = ImageTk.PhotoImage(image2.resize((600, 400)))
    label2 = Label(fifth, image=img2)
    label2.image = img2
    label2.pack()

    image3 = Image.open(r"C:\Users\29212\Desktop\results2.jpg")
    zoom = 1.8
    pixels_x3, pixels_y3 = tuple([int(zoom * x) for x in image3.size])
    img3 = ImageTk.PhotoImage(image3.resize((600, 400)))
    label3 = Label(fifth, image=img3)
    label3.image = img3
    label3.pack()

btn6 = Button(fourth, text="最终结果显示", width=8, command=f)
btn6.place(x=600, y=280)

image1 = Image.open(r"C://Users//29212//Desktop//mbti1.jpg")
zoom = 1.8
pixels_x1, pixels_y1 = tuple([int(zoom * x) for x in image1.size])
img1 = ImageTk.PhotoImage(image1.resize((600, 400)))
label1 = Label(root, image=img1)
label1.image = img1
label1.pack()

修改后的代码中,将原来的fifth变量的定义移到了f函数之外,并将其作为全局变量。在f函数中,先调用fifth的update方法,确保之前的窗口更新,然后销毁之前的fifth窗口。接着重新创建一个新的fifth窗口,并在该窗口中创建新的label2和label3控件,并将它们绑定到新的fifth窗口上。

这样,在点击“最终结果显示”按钮时,会先更新之前的窗口,然后销毁之前的窗口,并创建一个新的窗口来显示label2和label3控件所对应的图片。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^