python十六进制编辑器

源代码:

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()

 

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值