【问题标题】:Python Tkinter Display Image [duplicate]Python Tkinter显示图像[重复]
【发布时间】:2021-05-18 15:21:19
【问题描述】:

我正在尝试编写一个简单的脚本来使用 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()

谢谢!

【问题讨论】:

  • 将file="..."更改为file=r"..."

标签: python tkinter python-imaging-library


【解决方案1】:

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")

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

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

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

【讨论】:

  • 顺便说一句,我不知道为什么,但是 python 将 "\Sandip" 转换为 \\Sandip" 所以你唯一需要转义反斜杠的时候是当你有 "\U..." 时。所以file="C:\\Users\Sandip Dhillon\Pictures\DESlogo1.png" 也应该可以工作。我认为是因为"\u..." 用于启动 Unicode 转义序列。
  • 是的,它应该可以工作,但最好转义所有内容,而不必记住'"abfnrtvxNuU 是转义序列的一部分:)
  • o 代表什么? Python 将"\o" 转换为"\\o"(自动转义反斜杠)。
  • @TheLizzard 哎呀,我的意思是"\123"(八进制序列)。
  • 感谢帮助了很多人,它现在正在工作。感谢它,@TheLizzard 你又来救我了哈哈
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-22
  • 2017-12-24
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
相关资源
最近更新 更多