如何使用Tkinter在Python上上传图像?
我正在Python上使用Tkinter进行GUI编程。我正在使用网格管理器制作小部件。我已经创建了几个按钮,我想上传它们上面的图像。当我输入此代码时,它会给我一个如何使用Tkinter在Python上上传图像?,python,user-interface,tkinter,widget,Python,User Interface,Tkinter,Widget,我正在Python上使用Tkinter进行GUI编程。我正在使用网格管理器制作小部件。我已经创建了几个按钮,我想上传它们上面的图像。当我输入此代码时,它会给我一个转义序列错误 我听说使用PIL不是个好主意?这是真的吗 cookImage = PhotoImage(file = "image/C:\Users\terimaa\AppData\Local\Programs\Python\Python36-32\cook.gif") Windows文件名必须作为原始字符串输入: cookImage
转义序列错误
我听说使用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”
- 相对(
,取决于Python代码的位置)“\cook.gif”
位图图像
或照片图像
打开即可。请注意,Tcl/Tk 8.6(您应该在Windows上使用3.6)也读取.png文件。在Windows上,使用“r”作为文件名前缀或使用前斜杠:“C:/User/…”
实际的PIL包不再维护,只在2.x上工作。这是新用户不应该使用的。兼容的后续版本,
pillow
(例如,通过python-mpipinstallpillow
安装)被积极维护并与3.x配合使用。兼容性扩展到import语句:import-PIL
imports。枕头允许人们操作图像,并将多种格式转换为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上成功运行请显示确切的错误。必须是一个相当强的术语。您也可以使用前斜杠,也可以使用用反斜杠转义的后斜杠。@BryanOakley很公平,但原始字符串是最干净的方式。我从不推荐前斜杠,因为它们只起作用。