介绍:
在编程中,涉及到文件,会有不同的编码格式。这个小工具主要是以各种编码打开相关文件,编辑后,还可以各种编码格式保存。
使用注意:
在要保存二进制文件的时候,相邻的两个二位16禁止数需要用空格隔开。
知识点:
tkinter界面涉及(包含按钮-button、下拉列表-ttk.Combobox、滑动文本框-scrolledtext.ScrolledText),文件读写(open、read、write)
界面展示:
代码:
from tkinter import *
from tkinter import filedialog,scrolledtext,ttk
import re
LIST_CODER=('gbk','utf-8','ASCII','ANSI','二进制')
win_main = Tk()
win_main["background"] = "gray"
win_main.geometry('1000x600')
win_main.resizable(False,False)
win_main.title("图片摘取文字")
value_cbox_Open=StringVar()
cbox_Open=ttk.Combobox(win_main,textvariable=value_cbox_Open,values=LIST_CODER)
cbox_Open.current(0)
cbox_Open.place(x=0,y=0,width=100,height=25)
def cmd_btn_Open():
fileName=filedialog.askopenfilename(title='打开文件')
try:
if value_cbox_Open.get() == '二进制':
file_open=open(fileName,'rb')
else:
file_open = open(fileName, 'r',encoding=value_cbox_Open.get())
str_read=file_open.read()
file_open.close()
stxt_Show.delete(0.0,END)
if value_cbox_Open.get() == '二进制':
print(type(str_read))
for i in range(len(str_read)):
str_temp = '{:0>2x}'.format(str_read[i])
stxt_Show.insert(END, str_temp)
if (i+1)%45==0 and i>0:
stxt_Show.insert(END,'\n')
else:
stxt_Show.insert(END, ' ')
else:
stxt_Show.insert(END,str_read)
except BaseException as e:
stxt_Show.delete(0.0, END)
stxt_Show.insert(END, '文件打开错误:'+str(e))
return
btn_Open=Button(win_main,text='打开文件',command=cmd_btn_Open)
btn_Open.place(x=100,y=0,width=100,height=25)
value_cbox_Save=StringVar()
cbox_Save=ttk.Combobox(win_main,textvariable=value_cbox_Save,values=LIST_CODER)
cbox_Save.current(0)
cbox_Save.place(x=200,y=0,width=100,height=25)
def cmd_btn_Save():
a=btn_Open.cget('font')
print(a,type(a))
fileName=filedialog.asksaveasfilename(title='保存文件')
try:
if value_cbox_Open.get() == '二进制':
file_open=open(fileName,'wb')
else:
file_open = open(fileName, 'w',encoding=value_cbox_Open.get())
str_write=stxt_Show.get(0.0,END)
str_write=re.split('[^0-9^a-f^A-F]',str_write)
if value_cbox_Open.get() == '二进制':
list_int_write = []
for i in range(len(str_write)):
if str_write[i]!='':
list_int_write.append(int(str_write[i],16))
file_open.write(bytes(list_int_write))
else:
file_open.write(str_write)
file_open.close()
except BaseException as e:
stxt_Show.delete(0.0, END)
stxt_Show.insert(END, '文件保存错误:'+str(e))
return
btn_Save=Button(win_main,text='保存文件',command=cmd_btn_Save)
btn_Save.place(x=300,y=0,width=100,height=25)
stxt_Show=scrolledtext.ScrolledText(win_main)
stxt_Show.place(x=0,y=25,width=1000,height=575)
win_main.mainloop()