【问题标题】:Image not displaying in python Tkinter in UI [duplicate]UI中的python Tkinter中未显示图像[重复]
【发布时间】:2016-05-17 07:58:59
【问题描述】:

我正在尝试使用 Tkinter 模块在 python 2.7 中创建一个简单的 UI,以浏览和选择图像并将其显示在 UI 上,但是当我浏览并选择图像时,屏幕上的当前图像(初始加载的图像)变得清晰但所选图像未显示在屏幕上。

from Tkinter import * 
from PIL import ImageTk, Image
import tkFileDialog

root = Tk()
root.title('Simple Image Display app')

w = Canvas(root, width=1100, height=600)
w.pack()
root.resizable(width=FALSE, height=FALSE)

img = ImageTk.PhotoImage(Image.open('test_2.JPG').convert('LA'))
panel = Label(root, image = img)
panel.place(x=700,y=100)


def Open():       ## function to open file dialog and select the file to use in the reader application
    dialog = Tk()
    dialog.withdraw()
    fname = tkFileDialog.askopenfilename(filetypes = (("Image Files", "*.JPG"), ("All files", "*")))
    dialog.destroy()
    img = ImageTk.PhotoImage(Image.open(fname).convert('LA'))
    panel.configure(image = img)



menubar = Menu(root)

# File Menu
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Open", command=Open)
menubar.add_cascade(label="File", menu=filemenu)


# display the menu
root.config(menu=menubar)
root.mainloop()

在解决问题方面有什么帮助或建议吗?

提前致谢。

【问题讨论】:

  • 控制台有错误吗?

标签: python tkinter python-imaging-library


【解决方案1】:

看起来有人以前在 SO 上遇到过这个问题:How to update the image of a Tkinter Label widget?

归结为Tkinter 在图像上执行garbage collection,因此超出范围。您想在 panel.configure(...) 行下方添加 panel.image = img

【讨论】:

    【解决方案2】:

    根据@nicholas-smith 的建议更改后,我的代码运行良好。 这是python 2.7的更新和工作代码

    def Open():       ## function to open file dialog and select the file to use in the reader application
        dialog = Tk()
        dialog.withdraw()
        fname = tkFileDialog.askopenfilename(filetypes = (("Image Files", "*.JPG"), ("All files", "*")))
        dialog.destroy()
        img2 = ImageTk.PhotoImage(Image.open(fname).convert('LA'))
        panel.configure(image = img2)
        panel.image = img2
    

    只有“打开”功能需要修改。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-10
      • 2017-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-12
      • 2011-03-22
      • 2021-05-11
      相关资源
      最近更新 更多