图片挑选工具(python TK小工具)
打开本地文件夹图片,另存图片到目标文件夹:
1、显示图片;
2、按钮按下,显示上一张图片,下一张图片;
3、跳转按钮可以跳转到指定图片位置;
4、另存图片
import tkinter as tk
from tkinter import messagebox, filedialog
from PIL import Image, ImageTk
import os
# 主窗口
root = tk.Tk()
root.geometry("1200x850")
root.title('图片挑选器')
# 另存路径
img_save = "./tmp1/"
# 选择文件夹
folder = filedialog.askdirectory(parent=root,
initialdir=os.getcwd(),
title="Please select a folder:")
# 将文件夹中的所有图片读到数组中,这里是图片路径的集合
PngList = os.listdir(folder)
if not len(PngList):
print('文件中没有图片')
os._exit(0) # 文件夹中没有jpg图片就退出
nIndex = 0 # 记录显示图片的文件下标
def resize(nX, nY):
xNew = 1200
yNew = int(nY * 1200 / nX)
return (xNew, yNew)
def submit():
global nIndex
global photo
global imglabel
print(PngList[nIndex])
strPng = folder + '//' + PngList[nIndex]
photo = ImageTk.PhotoImage(file=strPng) # 打开图片看分辨率,如果太大则需要调整
imglabel = tk.Label(root, image=photo)
imglabel.place(x=0, y=0)
photoNew = Image.open(strPng).resize(resize(photo.width(), photo.height())) # 00调整图片的分辨率
photo = ImageTk.PhotoImage(photoNew)
imglabel.config(image=photo)
nIndex = nIndex + 1
if nIndex == len(PngList):
nIndex = len(PngList)
r = messagebox.showinfo('消息框', '已经是最后一张图片')
print('showinfo:', r)
submit()
def jumpTo():
global nIndex
nIndex = int(enTextJumNum.get('0.0', 'end'))
print(nIndex)
submit()
# 上一个
def pre():
global nIndex
nIndex = nIndex - 2
if nIndex < 0:
nIndex = 0
r = messagebox.showinfo('消息框', '已是首张图片')
print('showinfo:', r)
print(nIndex)
submit()
# 首页
def home():
global nIndex
nIndex = 0
print(nIndex)
submit()
def onEventNext(e):
submit()
def onEventPre(e):
pre()
def save_img():
"""
图片另存
"""
global nIndex
print("img_num=", nIndex)
like_img = Image.open(folder + '/'+PngList[nIndex-1])
like_img.save(img_save + PngList[nIndex-1])
print("success!")
# 上一张
btnPre = tk.Button(root, text="上一个", command=pre)
btnPre.place(x=200, y=800)
# 下一张
btnNext = tk.Button(root, text="下一个", command=submit)
btnNext.place(x=280, y=800)
# 首页
btnPre = tk.Button(root, text="首张", command=home)
btnPre.place(x=120, y=800)
# 另存图片
saveImg = tk.Button(root, text="保存", command=save_img)
saveImg.place(x=360, y=800)
# 输入控件
enTextJumNum = tk.Text(root)
enTextJumNum.place(x=500, y=800, height=20, width=58)
enTextJumNum.insert(tk.INSERT, '0')
# 跳转控件
btnjump = tk.Button(root, text="跳转", command=jumpTo)
btnjump.place(x=600, y=800)
root.bind("<MouseWheel>", onEventNext)
root.bind("<Down>", onEventNext)
root.bind("<Right>", onEventNext)
root.bind("<Up>", onEventPre)
root.bind("<Left>", onEventPre)
tk.mainloop()
参考
链接: link