Certainly! Below is a simple example of a custom text encoding in Python, along with a GUI using tkinter that allows you to read a text file, encode it, and decode it back.
For demonstration, let's use a simple encoding: shift each character's Unicode code point by +3 (like a Caesar cipher, but for all characters).
1. The Encoder and Decoder
def encode(text):
return ''.join(chr((ord(char) + 3) % 0x110000) for char in text)
def decode(text):
return ''.join(chr((ord(char) - 3) % 0x110000) for char in text)
2. The GUI Reader/Encoder/Decoder
import tkinter as tk
from tkinter import filedialog, messagebox, scrolledtext
def encode(text):
return ''.join(chr((ord(char) + 3) % 0x110000) for char in text)
def decode(text):
return ''.join(chr((ord(char) - 3) % 0x110000) for char in text)
class TextEncoderGUI:
def __init__(self, root):
self.root = root
self.root.title("Custom Text Encoder/Decoder")
# Text area
self.text_area = scrolledtext.ScrolledText(root, width=60, height=20)
self.text_area.pack(padx=10, pady=10)
# Buttons
btn_frame = tk.Frame(root)
btn_frame.pack(pady=5)
tk.Button(btn_frame, text="Open File", command=self.open_file).pack(side=tk.LEFT, padx=5)
tk.Button(btn_frame, text="Encode", command=self.encode_text).pack(side=tk.LEFT, padx=5)
tk.Button(btn_frame, text="Decode", command=self.decode_text).pack(side=tk.LEFT, padx=5)
tk.Button(btn_frame, text="Save As...", command=self.save_file).pack(side=tk.LEFT, padx=5)
def open_file(self):
file_path = filedialog.askopenfilename(filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")])
if file_path:
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
self.text_area.delete(1.0, tk.END)
self.text_area.insert(tk.END, content)
def encode_text(self):
text = self.text_area.get(1.0, tk.END)
encoded = encode(text)
self.text_area.delete(1.0, tk.END)
self.text_area.insert(tk.END, encoded)
def decode_text(self):
text = self.text_area.get(1.0, tk.END)
decoded = decode(text)
self.text_area.delete(1.0, tk.END)
self.text_area.insert(tk.END, decoded)
def save_file(self):
file_path = filedialog.asksaveasfilename(defaultextension=".txt",
filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")])
if file_path:
with open(file_path, "w", encoding="utf-8") as f:
f.write(self.text_area.get(1.0, tk.END))
messagebox.showinfo("Saved", f"File saved to {file_path}")
if __name__ == "__main__":
root = tk.Tk()
app = TextEncoderGUI(root)
root.mainloop()
How it works
- Open File: Load a text file into the text area.
- Encode: Encodes the text using the custom encoding.
- Decode: Decodes the text back to the original.
- Save As...: Save the current text area content to a file.
You can expand the encoding/decoding logic as needed!
Let me know if you want a more complex encoding or additional features.