【问题标题】:How do I put an image in python tkinter?如何在 python tkinter 中放置图像?
【发布时间】:2020-12-09 01:51:35
【问题描述】:

我正在尝试将 JPEG 图像插入 Python Tkinter 窗口,但它不起作用。我试过这个:

imageFile = "logo.jpg"
window.im1 = Image.open(imageFile)

当我运行它时说:

line 21, in <module>
window.im1 = Image.open(imageFile)
AttributeError: type object 'Image' has no attribute 'open'

我试过了:

imageFile = "logo.jpg"
window.im1 = PhotoImage.open(imageFile)

但它说:

line 20, in <module>
window.im1 = PhotoImage.open(imageFile)
AttributeError: type object 'PhotoImage' has no attribute 'open'

我也试过了:

imageFile = "logo.jpg"
window.im1 = Image(imageFile)

但它说:

line 4006, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: image type "logo.jpg" doesn't exist

最后,我尝试了:

imageFile = "logo.jpg"
window.im1 = PhotoImage(imageFile)

运行正常,但什么也没显示。

有没有其他方法可以放图片?

我发现了!

【问题讨论】:

  • edit 您的问题包含完整的minimal reproducible example。至少我们需要看看Image是如何定义的。
  • Bryan,我正在寻找一种完全不同的方式,同样,我什至不知道,因为我从某处复制了它。
  • 查看tutorial 以供参考,我复制并粘贴了他们的代码,它可以工作。如果您仍有问题,请按照 Bryan 的建议提供您的代码的准系统,以便我们了解您的 2-3 行代码如何与其余代码交互。
  • 安德鲁,成功了!谢谢。
  • 不客气!很高兴我能帮上忙

标签: python image tkinter


【解决方案1】:

希望对你有帮助

from PIL import Image, ImageTk
    from tkinter import Tk, Frame, Label
     
    class Example(Frame):
      def __init__(self, parent):
        Frame.__init__(self, parent)
      
        self.parent = parent
      
        self.initUI()
      
      def initUI(self):
        self.parent.title("Label")
      
        self.img = Image.open("C:\\tatras.jpg")
        tatras = ImageTk.PhotoImage(self.img)
        label = Label(self, image=tatras)
      
        label.image = tatras
      
        label.pack()
        self.pack()
      
      def setGeometry(self):
        w, h = self.img.size
        self.parent.geometry(("%dx%d+300+300") % (w, h))
      
    root = Tk()
    ex = Example(root)
    ex.setGeometry()
    root.mainloop()

输出

Image

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    • 2015-05-21
    • 2015-10-05
    • 2013-06-29
    • 2017-02-14
    相关资源
    最近更新 更多