【问题标题】:why function does not work to get display image on label tkinter python, but it works not using function为什么函数不能在标签 tkinter python 上显示图像,但它不能使用函数
【发布时间】:2021-03-01 06:27:03
【问题描述】:

这个没有函数的代码确实可以在标签 tkinter python 3.8.5 上显示图像。

    from tkinter import *
    from PIL import Image, ImageTk
    import os
    import os.path

    root = Tk()
    root.title("Test_image")
    root.geometry("1000x600")

    # def display_image():
    images_folder = "C:/TextSoundSource/B-V/I-WORD-E-00-B-V-0-renamed"
    os.chdir(images_folder)
    displaying_img = "022.jpg"

    # Open Image
    img = Image.open(displaying_img)

    # Resize Image
    resized = img.resize((300, 200), Image.ANTIALIAS)
    resized_img = ImageTk.PhotoImage(resized)

    image_display_frame = LabelFrame(root, text="Image", font=(
         "times", 15, "bold"), bg="Navyblue", fg="white", bd=5)
    image_display_frame.place(x=0, y=0, width=1000, height=300)

    img_label = Label(image_display_frame, image=resized_img)

    img_label.pack(pady=20)

    # display_image()
    root.mainloop()

但是当使用下面这样的函数时它不起作用,我如何使用函数获取图像?

    from tkinter import *
    from PIL import Image, ImageTk
    import os
    import os.path

    # == == == == == == == == == == == ======== 
    # Using function does not work ???? why ???
    # == == == == == == == == == == == ========

    root = Tk()
    root.title("Test_image")
    root.geometry("1000x600")

    def display_image():
        images_folder = "C:/TextSoundSource/B-V/I-WORD-E-00-B-V-0-renamed"
        os.chdir(images_folder)
        displaying_img = "001.jpg"

        # Open Image
        img = Image.open(displaying_img)

        # Resize Image
        resized = img.resize((300, 200), Image.ANTIALIAS)

        resized_img = ImageTk.PhotoImage(resized)

        image_display_frame = LabelFrame(root, text="Image", font=(
            "times", 15, "bold"), bg="Navyblue", fg="white", bd=5)
        image_display_frame.place(x=0, y=0, width=1000, height=300)

        img_label = Label(image_display_frame, image=resized_img)
        img_label.pack(pady=20)

    display_image()
    root.mainloop()

提前感谢,请告诉我如何使用 tkinter python 中的函数获取图像显示。

【问题讨论】:

  • 在函数中添加 global resized_img 或仅添加 root.anything = resized_img

标签: python image tkinter


【解决方案1】:

在 Python 中,函数具有自己的对象名称本地范围。当您退出该函数时,所有名称都会被垃圾回收,并且对程序不可用。

正如@Cool cloud 建议的那样,您可以使用global 关键字将图像引用添加到全局范围。另一种常见的技术是将图像引用保存到标签小部件:

img_label.image = resized_img

【讨论】:

  • 这对我来说是一个非常有用的关键答案。它有效。
猜你喜欢
  • 1970-01-01
  • 2021-04-13
相关资源
最近更新 更多