python - 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()
谢谢!
解决方案
反斜杠是 Python 字符串中的转义字符,因此您的字符串以一种有趣的方式解释。
任何一个:
- 使用正斜杠:
tk.PhotoImage(file="C:/Users/Sandip Dhillon/Pictures/DESlogo1.png")
- 使用
r
aw 字符串:tk.PhotoImage(file=r"C:\Users\Sandip Dhillon\Pictures\DESlogo1.png")
字符串和字节文字都可以选择以字母“r”或“R”作为前缀;此类字符串称为原始字符串,并将反斜杠视为文字字符。
- 双斜杠:
tk.PhotoImage(file="C:\\Users\\Sandip Dhillon\\Pictures\\DESlogo1.png")
转义序列:
\\
: 反斜杠 (\
)
推荐阅读
- python - 如果条件不适用于“False”值,为什么python?
- android - Android Studio 插入 mp3 声音
- c# - 该游戏无法在 Instant Games Facebook 中加载。如何解决问题?
- coq - 减少列表元素
- azure-devops - 如何从 AzureDevOps 发布管道中的特定分支下载代码
- ansible - 在 ansible playbook 中需要帮助以根据特定条件压缩文件和排除文件
- blockchain - 是否可以创建我们自己的 Solidity 库?
- haskell - Haskell如何添加可以处理Maybe列表的实例
- typescript - 打字稿可以处理不基于函数参数的动态返回类型吗?
- c# - 将电子邮件保存到具有指定文件名的目录在 .NET 5.0 中不起作用