源代码:
import tkinter as tk
from tkinter import filedialog
import struct
import binascii
import os
class HexEditor:
def __init__(self, master):
self.master = master
self.master.title("十六进制编辑器")
self.master.configure(bg='black')
self.master.geometry("800x450+200+200")
self.scrollbar = tk.Scrollbar(master)
self.scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.text_area = tk.Text(master, width=80, height=30, bg='black', fg='white', yscrollcommand=self.scrollbar.set)
self.text_area.pack(expand=True, fill=tk.BOTH)
self.scrollbar.config(command=self.text_area.yview)
self.open_button = tk.Button(master, text="打开文件", command=self.open_file, bg='gray', fg='white')
self.open_button.pack()
self.save_button = tk.Button(master, text="保存文件", command=self.save_file, bg='gray', fg='white')
self.save_button.pack()
def open_file(self):
file_path = filedialog.askopenfilename()
if file_path:
try:
with open(file_path, 'rb') as file:
data = file.read()
self.display_hex_data(data)
except FileNotFoundError:
tk.messagebox.showerror("错误", "文件未找到")
except PermissionError:
tk.messagebox.showerror("错误", "没有访问权限")
def display_hex_data(self, data):
self.text_area.delete('1.0', tk.END)
hex_str = binascii.hexlify(data).decode('utf-8')
spaced_hex_str =' '.join([hex_str[i:i + 2] for i in range(0, len(hex_str) - 1, 2)])
self.text_area.insert(tk.END, spaced_hex_str + '\n')
def save_file(self):
file_path = filedialog.asksaveasfilename(defaultextension=".hex")
if file_path:
hex_str = self.text_area.get('1.0', tk.END)
hex_str = hex_str.replace(' ', '') # 去除用户输入的空格
hex_str = ''.join(e for e in hex_str if e in '0123456789abcdefABCDEF') # 去除非十六进制字符
data = binascii.unhexlify(hex_str)
with open(file_path, 'wb') as file:
file.write(data)
root = tk.Tk()
editor = HexEditor(root)
root.mainloop()