如下程序实现功能:选择本机路径,根据所选路径显示对应图片
实现要点包括:
1、选择路径
2、图片大小重置
3、根据路径展示图片
完整程序如下:
# -*- coding: utf-8 -*-
"""
Created on Mon May 13 16:33:15 2019
@author: hx
"""
# 举个栗子,添加输入框,将验证码图片打印出来
# coding= utf-8
from PIL import ImageTk
from tkinter import filedialog as fd
#from tkinter import *
import PIL
import tkinter as tk
#import os
class GetCode(object):
def __init__(self):
self.root = tk.Tk()
# 设置整个顶层GUI页面长宽可拉伸
self.root.resizable(width=True,height=True)
self.path = tk.StringVar()
#grid布局管理器,与pack功能类似:https://www.cnblogs.com/ruo-li-suo-yi/p/7425307.html
tk.Label(self.root,text = "待识别图片路径:").grid(row = 0, column = 0)
#输入、输出框存放选择路径
tk.Entry(self.root, textvariable = self.path, width=113).grid(row = 0, column = 1)
tk.Button(self.root, text = "待识别图片选择", command = self.selectPath).grid(row = 0, column = 2)
#tk.Label(self.root,text = "识别后生成文件路径:").grid(row = 1, column = 0)
#输入、输出框存放识别后生成文件路径
#tk.Entry(self.root, textvariable = "假的", width=113).grid(row = 1, column = 1)
#保留后续根据图片识别图片,且将生成的识别文件存于某个路径
#tk.Button(self.root,text="识别图片文字",command=self.return_code).grid(row = 1, column = 2) # 按键
self.root.mainloop()
def return_code(self):
self.root.destroy() # 关闭窗体
#os.remove(self.path.get()) # 删除图片
#识别图片
#返回文件路径,存于输入输出框
def selectPath(self):
path_ = fd.askopenfilename()
self.path.set(path_)
#选测路径之后进行图片展示
self.showPhoto(self.path.get())
#重置图片(按要求缩放)
def resize(self, w_box, h_box, pil_image): #参数是:要适应的窗口宽、高、Image.open后的图片
w, h = pil_image.size #获取图像的原始大小
f1 = 1.0*w_box/w
f2 = 1.0*h_box/h
factor = min([f1, f2])
width = int(w*factor)
height = int(h*factor)
return pil_image.resize((width, height), PIL.Image.ANTIALIAS)
#open_path为选择图片的路径
def showPhoto(self,open_path):
#期望图像显示的大小
w_box = 800
h_box = 800
# get the size of the image
#根据选择的路径显示图片
im=PIL.Image.open(open_path)
# resize the image so it retains its aspect ration
# but fits into the specified display box
#缩放图像让它保持比例,同时限制在一个矩形框范围内
im_resize = self.resize(w_box, h_box, im)
img=ImageTk.PhotoImage(im_resize)
tk.Label(self.root,image=img).grid(row = 2, column = 1) # 布局控件
self.root.mainloop() #显示图片
if __name__ == '__main__':
GetCode()
效果如下:
1、点击按钮
2、选择路径
3、显示缩放之后的图片
喜欢我的文章希望和我一起成长的宝宝们,可以搜索并添加公众号TryTestwonderful ,或者扫描下方二维码添加公众号