如何在不使用PIL模块的情况下插入图像?

时间:2018-03-04 13:05:19

标签: python tkinter

LH=Label(LowerHeading, font=('arial',12,'bold'), text ="Update", bd = 10, width = 15, anchor = 'w')
LH.grid(row=1,column=0)
path = 'C:/Users\Ermira1\Documents\Ermira\1. Sixth Form\Year 13\Computer Science/dress.jpg'
photo = PhotoImage(file="path")
LeftLower= Frame(text=photo)

由于某种原因,这不起作用,我不知道为什么。

错误消息显示如下:

Traceback (most recent call last):
  File "C:\Users\Ermira1\Documents\Ermira\1. Sixth Form\Year 13\Computer Science\Inventory (new).py", line 163, in <module>
    photo = PhotoImage(file="path")
  File "C:\Python34\lib\tkinter\__init__.py", line 3416, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\Python34\lib\tkinter\__init__.py", line 3372, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "path": no such file or directory
>>> 

1 个答案:

答案 0 :(得分:1)

即时错误是您尝试从名为"path"的地方获取图片,这绝不是路径,您可能需要path

photo = PhotoImage(file=path)

然后会产生另一个错误,因为path的字符串也是错误的,它使用\/不一致;并且由于\是一个以某种方式修改字符串的转义字符,您应该用double(\\)替换它们以转义转义字符本身,或者使用原始字符串格式r"my string such as path" 。所以替换为:

path = r'C:\Users\Ermira1\Documents\Ermira\1. Sixth Form\Year 13\Computer Science\dress.jpg'

或:

path = 'C:\\Users\\Ermira1\\Documents\\Ermira\\1. Sixth Form\\Year 13\\Computer Science\\dress.jpg'
  

"How to insert an image without using the PIL module?"

首先,你不能不使用额外的库(无论如何) 或其他内容),除非支持该格式(例如,jpg,不支持)。

其次,可以通过多种方式插入图像,为了清晰起见,我们使用标签进行显示。

下面的代码首先下载图像(如果图像已经存在,可以完全替换),然后它会尝试显示.png(在版本的版本中支持晚于8.6),如果可以的话't display .png然后它会尝试显示.gif:

try:                        # In order to be able to import tkinter for
    import tkinter as tk    # either in python 2 or in python 3
except ImportError:
    import Tkinter as tk


def download_images():
    # In order to fetch the image online
    try:
        import urllib.request as url
    except ImportError:
        import urllib as url
    url.urlretrieve("https://i.stack.imgur.com/IgD2r.png", "lenna.png")
    url.urlretrieve("https://i.stack.imgur.com/sML82.gif", "lenna.gif")


if __name__ == '__main__':
    download_images()
    root = tk.Tk()
    widget = tk.Label(root, compound='top')
    widget.lenna_image_png = tk.PhotoImage(file="lenna.png")
    widget.lenna_image_gif = tk.PhotoImage(file="lenna.gif")
    try:
        widget['text'] = "Lenna.png"
        widget['image'] = widget.lenna_image_png
    except:
        widget['text'] = "Lenna.gif"
        widget['image'] = widget.lenna_image_gif
    widget.pack()
    root.mainloop()