首页 > 解决方案 > Python Tkinter 显示图像

问题描述

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

我尝试使用 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()

谢谢!

标签: pythontkinterpython-imaging-library

解决方案


反斜杠是 Python 字符串中的转义字符,因此您的字符串以一种有趣的方式解释。

任何一个:

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

    字符串和字节文字都可以选择以字母“r”或“R”作为前缀;此类字符串称为原始字符串,并将反斜杠视为文字字符。

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

    转义序列: \\: 反斜杠 ( \)


推荐阅读