Tkinter通过filedialog打开文件夹打开jpg格式图片并显示

参考

代码中的细节方面可以参看:TKinter部件用法总结

代码

from tkinter import *
import os
from tkinter import messagebox, filedialog
import imageio
from PIL import Image, ImageTk


class Application(Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.place()
        self.createWidget()

    def createWidget(self):
        global photo
        photo = None
        self.label03 = Label(self, image=photo)
        self.label03.grid(column=0, row=0)
        # self.label03.place(relx=0.5, rely=0.5, anchor=CENTER)

        self.btn01 = Button(self, text='打开', command=self.getfile, bg='white', anchor='s')
        self.btn01.grid(column=0, row=1)
        # self.btn01.place(relx=0.8, rely=0.5, anchor=CENTER)

    def getfile(self):
        file_path = filedialog.askopenfilename(title='选择文件', filetypes=[(('JPG', '*.jpg')), ('All Files', '*')])
        img = Image.open(file_path)
        width, height = img.size
        
        img =  img.resize((700, int(700/width*height)))

        global photo
        photo = ImageTk.PhotoImage(img)  # 实际上是把这个变成全局变量
        self.label03.configure(image = photo)
        self.label03.image = photo

root = Tk()
root.geometry('700x680')
app = Application(master=root)

root.mainloop()

示例

运行示例:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值