在Tkinter Python程序中无法看到图片

4nkexdtk  于 2022-12-20  发布在  Python
关注(0)|答案(1)|浏览(126)
topper = Toplevel()
topper.title("2nd Window")
topper.state('zoomed')
my_img = ImageTk.PhotoImage(Image.open("diamond.png"))
my_label = Label(topper, image=my_img, height = 100 , width = 100)
F21 = Frame(topper, borderwidth=83, bg="blue", relief=SUNKEN)
button1 = Button(topper, text="class", command=topper.destroy)
button1.pack()
my_label.pack()

我正在运行代码,我没有得到错误,按钮是工作以及,但我不能看到窗口中的图片。

9q78igpj

9q78igpj1#

欢迎来到我们的网站!
对于将来-提供Minimal, Reproducible Example总是好的,这样其他人就可以复制和更好地理解您的问题,以便帮助您!它还可以帮助您了解错误的确切来源。
当你从另一个tkinter窗口调用Toplevel()来打开一个新窗口时,你还需要在第二个窗口调用“mainloop()”来显示一个图像--试试我的代码中的一个示例图像,并使用注解/取消注解该行

topper.mainloop()

以查看功能上的差异。
修改后的代码:

from tkinter import *
from PIL import Image, ImageTk   # pip install pillow

def show_second_window():
    topper = Toplevel()
    topper.title("2nd Window")
    topper.state('zoomed')
    my_img = ImageTk.PhotoImage(Image.open("t1.png"))
    my_label = Label(topper, image=my_img, height=100, width=100)
    F21 = Frame(topper, borderwidth=83, bg="blue", relief=SUNKEN)
    button1 = Button(topper, text="class", command=topper.destroy)
    button1.pack()
    my_label.pack()

    topper.mainloop()  # <---- this is needed to show the image!

root = Tk()
root.title("1st window")
button = Button(root, text="show second window", command=show_second_window)
button.pack()
root.mainloop()

相关问题