我正在 Python 上使用 Tkinter 进行 GUI 编程。我正在使用网格管理器来制作小部件。我创建了几个按钮,我想在它们上面上传图像。当我输入此代码时,它会给我一个
escape sequence error
。
我听说使用 PIL 不是一个好主意?这是真的吗?
cookImage = PhotoImage(file = "image/C:\Users\terimaa\AppData\Local\Programs\Python\Python36-32\cook.gif")
Windows 文件名必须作为原始字符串输入:
cookImage = PhotoImage(file=r"C:\Users\terimaa\AppData\Local\Programs\Python\Python36-32\cook.gif")
这适用于所有 Python,而不仅仅是 PIL。
用途:
path = r"a string with the path of the photo"
注意
r
前缀,它表示原始字符串。
...
img = ImageTk.PhotoImage(Image.open(file=path))
label = tk.Label(root, image = img)
label.something() #pack/grid/place
...
路径可以是:
绝对(
"C:\Users\terimaa\AppData\Local\Programs\Python\Python36-32\cook.gif"
)相对(
"\cook.gif"
,取决于Python代码在哪里)如果您有一个正是您想要的图像文件,只需使用
BitmapImage
或PhotoImage
打开它即可。请注意,Tcl/Tk 8.6(Windows 上的 3.6 应该有)也读取 .png 文件。在 Windows 上,文件名前面加上“r”前缀或使用正斜杠:“C:/User/...”。
实际的 PIL 包不再维护,仅适用于 2.x。这是新用户不应该使用的。兼容的后继者
pillow
(例如与 python -m pip install pillow
一起安装)得到积极维护并可与 3.x 一起使用。兼容性扩展到导入声明:import PIL
导入枕头。 Pillows 允许操作图像并将多种格式转换为 tk 格式(ImageTk 类)。
这是对移动图像最有帮助的确切代码
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
import os, shutil
class Root(Tk):
def __init__(self):
super(Root,self).__init__()
self.title("thinter Dialog Widget")
self.minsize(640,400)
self.labelFrame = ttk.LabelFrame(self,text="Open A File")
self.labelFrame.grid(column=0,row=1,padx= 20, pady= 20)
self.btton()
def btton(self):
self.button = ttk.Button(self.labelFrame, text="Browse Afile", command=self.fileDailog)
self.button.grid(column=1,row=1)
def fileDailog(self):
self.fileName = filedialog.askopenfilename(initialdir = "/", title="Select A File",filetype=(("jpeg","*.jpg"),("png","*.png")))
self.label = ttk.Label(self.labelFrame, text="")
self.label.grid(column =1,row = 2)
self.label.configure(text = self.fileName)
os.chdir('e:\\')
os.system('mkdir BACKUP')
shutil.move(self.fileName,'e:\\')
if __name__ == '__main__':
root = Root()
root.mainloop()
由于权限被拒绝,您无法将图像移动到 C 盘:此代码在 python 3.8、3,7 上成功运行