打开本地图像
使用filedialog文件对话框可以对本地文件进行访问,并对其进行一系列处理,可选择以下方法进行访问:
方法 | 作用 |
---|---|
askopenfilename() | 选择打开什么文件,返回文件名 |
askopenfile | 选择打开什么文件,返回IO流对象 |
askopenfiles() | 选择打开多个文件,以列表形式返回多个IO流对象 |
asksaveasfilename() | 选择以什么文件名保存,返回文件名 |
asksaveasfile() | 选择以什么文件保存,创建文件并返回文件流对象 |
askdirectory() | 选择目录,返回目录名 |
askopenfilenames() | 选择打开多个文件,以元组形式返回多个文件名 |
import tkinter.filedialog
from tkinter import *
def click():
a=tkinter.filedialog.asksaveasfilename()#返回文件名
print(a)
a =tkinter.filedialog.asksaveasfile()#会创建文件
print(a)
a =tkinter.filedialog.askopenfilename()#返回文件名
print(a)
a =tkinter.filedialog.askopenfile()#返回文件流对象
print(a)
a =tkinter.filedialog.askdirectory()#返回目录名
print(a)
a =tkinter.filedialog.askopenfilenames()#可以返回多个文件名
print(a)
a =tkinter.filedialog.askopenfiles()#多个文件流对象
print(a)
root=Tk()
btn1=Button(root,text="click",command=click)
btn1.pack()
root.mainloop()
图像转码
在一些应用中,图片可能需要转换成编码格式来使用,所以我们可以用Base64的编码及解码的方法对其进行编码与解码,如下:
with open(path,"rb") as f:
# b64encode是编码,b64decode是解码
data = base64.b64encode(f.read())
print(data)
# 切割文件与扩展名
f,ext = os.path.splitext(path)
#print ( " ext is: " + ext)
format=ext.split('.')[1]
print(format)
base_data="data:image/"+format+";base64,"+str(data).split("'")[1]
print(base_data)
显示图片
tkinter本身打开图片的方法功能比较受限,所以我们可以利用专门处理图像的模块PIL进行辅助处理,其中Image可打开图像文件,ImageTK对其进行加载渲染:
path="file/img.png"
load = Image.open(path)
render = ImageTk.PhotoImage(load)
img = tkinter.Label(image=render)
img.image = render
img.place(x=200, y=100)