代码
import tkinter as tk
from PIL import Image, ImageTk
import sys
import tkinter. filedialog
def fill_image ( image) : width, height = image. size newImage_width = width if width > height else height newImage = Image. new( image. mode, ( newImage_width, newImage_width) , color= 'white' ) if width > height: newImage. paste( image, ( 0 , int ( ( newImage_width - height) / 2 ) ) ) else : newImage. paste( image, ( int ( ( newImage_width - width) / 2 ) , 0 ) ) return newImage
def cut_image ( image) : width, height = image. sizecolWidth = int ( width / 3 ) image_grid = [ ] for i in range ( 0 , 3 ) : for j in range ( 0 , 3 ) : row = ( j* colWidth, i* colWidth, ( j+ 1 ) * colWidth, ( i+ 1 ) * colWidth) image_grid. append( row) image_list = [ image. crop( row) for row in image_grid] return image_list
def save_images ( image_list) : index = 1 for image in image_list: image. save( str ( index) + '.png' , 'PNG' ) index+= 1
def select_button ( ) : global aa= tk. filedialog. askopenfilename( ) img = Image. open ( a) out = img. resize( ( 310 , 280 ) ) render = ImageTk. PhotoImage( out) img = tkinter. Label( image= render) img. image = renderimg. place( x= 30 , y= 60 ) txt. set ( a)
def cut_button ( ) : file_path= a image = Image. open ( file_path) image_new = fill_image( image) image_list = cut_image( image_new) save_images( image_list) label1. config( text= '切图成功!请在程序所在目录查看!' )
main= tk. Tk( )
main. geometry( '400x400' )
main. title( '明日九宫格切图器' )
main. iconbitmap( 'mr.ico' )
label1= tk. Label( main, text= '显示要切分图片的文件路径:' , fg= 'blue' )
label1. pack( )
txt = tkinter. StringVar( )
txt_entry = tkinter. Entry( main, width= 55 , textvariable= txt)
txt_entry. pack( )
button1= tk. Button( main, width= 10 , height= 1 , text= '选择图片' , fg= 'red' , bg= 'yellow' , command= select_button) . place( x= 30 , y= 360 )
button2= tk. Button( main, width= 10 , height= 1 , text= '切分图片' , fg= 'red' , bg= 'green' , command= cut_button) . place( x= 120 , y= 360 )
main. mainloop( )
效果