import tkinter as tk
from tkinter import filedialog#用于打开文件 核心:filepath = filedialog.askopenfilename() #获得选择好的文件,单个文件
import tkinter.messagebox #弹窗库
# from tkinter import Image
from PIL import Image#PIL需要安装 pip install pillow
from PIL import ImageTk
#myTK 初始化窗口 通过openfile函数来选择文件并显示
class myTK():
def __init__(self) -> None:
self.window=tk.Tk()#创建对象
self.window.title("转漫画风")#标题
# window.geometry("720x480")#设置窗口大小
self.window.geometry("1200x960")#设置窗口大小
self.window.resizable(height=False,width=False)#设置窗口不可改变大小
self.frame1=tk.Frame(self.window)
# self.frame1.place(x=0, y=100)
#打开文件按钮
self.bt_open = tk.Button(self.window,command=self.openfile, text='打开图片',height=2,width=10,activebackground='red')
self.bt_open.place(x=0, y=0)
self.window.mainloop()#显示
def openfile(self):#打开文件并显示
filepath = filedialog.askopenfilename() #获得选择好的文件,单个文件
imgtype=[".jpg",".png"]#规定读取的文件类型
if str(filepath)[-4:] in imgtype:
print("打开文件",filepath)
image = Image.open(filepath)
imgwidth,imgheight=image.size
self.frame1.destroy()
self.frame1=tk.Frame(self.window,bg="red",height=imgheight,width=imgwidth)
self.canvasimg=tk.Canvas(self.frame1,height=imgheight,width=imgwidth)
print(image.size)
im = ImageTk.PhotoImage(image)
self.canvasimg.create_image(0,0,anchor="nw",image=im)
self.canvasimg.place(x=0, y=0)
self.frame1.place(x=0, y=100)
self.laabel_img1.configure(image=im)#有bug才能显示图片?
else:
tkinter.messagebox.showinfo('提示','请选择.jpg .png 图片')
if __name__=="__main__":
mywindow=myTK()
#tkinter负责选择文件(获取文件路径,以及绘制可视化界面
#PIL image打开图片文件
#问题:图片更新问题没有解决,需要有bug才能正常显示,
#有大佬有想法可以一起讨论
python 使用tkinter 进行读取文件以及可视化界面显示
最新推荐文章于 2025-03-04 14:29:01 发布