Python Tkinter 显示图像

Python Tkinter Display Image

我正在尝试编写一个简单的脚本来使用 tkinter 在 window 中显示图像。

我尝试过使用 PIL/Pillow 并且尝试过使用标准的 tkinter 功能,但是当脚本尝试读取文件路径时总是出现相同的错误。

  File "c:/Users/Sandip Dhillon/Desktop/stuff/dev_tests/imgtest2.py", line 6
    photo=tk.PhotoImage(file="C:\Users\Sandip Dhillon\Pictures\DESlogo1.png")
                             ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

这是我的代码,

import tkinter as tk

window=tk.TK()
window.geometery("400x300+200+100")

photo=tk.PhotoImage(file="C:\Users\Sandip Dhillon\Pictures\DESlogo1.png")

l1=tk.Label(text="image")
l1.pack()
l2=tk.Label(image=photo)
l2.pack

window.mainloop()

谢谢!

Backslashes are escape characters in Python strings, so your string is interpreted in an interesting way.

或者:

  • 使用正斜杠:tk.PhotoImage(file="C:/Users/Sandip Dhillon/Pictures/DESlogo1.png")
  • 使用 raw 字符串:tk.PhotoImage(file=r"C:\Users\Sandip Dhillon\Pictures\DESlogo1.png")

    Both string and bytes literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and treat backslashes as literal characters.

  • 双斜线:tk.PhotoImage(file="C:\Users\Sandip Dhillon\Pictures\DESlogo1.png")

    Escape sequence: \: Backslash (\)