Default UTF-8 encoding for new Notepad documents

探讨如何在不使用第三方编辑器的情况下,配置Notepad使其默认保存文档为Unicode编码,解决原有编码导致的字符丢失问题。

转自:http://answers.microsoft.com/en-us/windows/forum/windows_7-windows_programs/default-utf-8-encoding-for-new-notepad-documents/525f0ae7-121e-4eac-a6c2-cfe6b498712c

Short of using a third party editor, is there a way to configure Notepad so that new documents are automatically saved in Unicode without having to change manually the encoding every single time from default ANSI to UTF-8?

Typical scenario:

- Start typing some text with no extended characters
- Save the file: It is automatically in ANSI
- Open the file again to edit, add some extended characters, save again:
Notepad tells you the extended characters will be lost if you confirm the save operation.

At least that last message offers the possibility to backup and "Save as" to choose UTF-8, but 1) this is very cumbersome, and 2) files with no extended characters will still be saved in ANSI by default.

Windows won't really be fully Unicode if the default Notepad encoding is still the obsolete ANSI code page, but, even if I reluctantly admit changing default behaviors is tricky for compatibility reasons, there should at least be a user option to select the default encoding for new documents, like other third party editors offer, such as Notepad++.

Currently, Windows forces me to replace Notepad file associations to use other text editors. Not a bad thing given the poor set of features in Notepad, but it would have been great to have this option in the standard O.S.


import tkinter as tk from tkinter import simpledialog, messagebox, filedialog, Menu import time import threading import json import uuid import os from datetime import datetime # ======================== # 工具函数 # ======================== def render_html(content): content = content.replace("<br>", "\n") content = content.replace("<p>", "\n").replace("</p>", "") content = content.replace("<h1>", "\n🔥 ").replace("</h1>", "\n") content = content.replace("<h2>", "\n📌 ").replace("</h2>", "\n") return content def round_button(parent, text, command, bg="#0078d7", fg="white"): btn = tk.Label(parent, text=text, bg=bg, fg=fg, font=('Segoe UI', 10), padx=15, pady=6, relief="flat", cursor="hand2", borderwidth=0) btn.bind("<Button-1>", lambda e: command()) btn.bind("<Enter>", lambda e: btn.config(bg="#005a9e")) btn.bind("<Leave>", lambda e: btn.config(bg=bg)) return btn # ======================== # 主类:Win12 Ultra VM v9.0(优化版) # ======================== class Win12UltraVM_Optimized: def __init__(self, root): self.root = root self.root.title("🌤️ Advanced Electronic Display OS v9.0 - Optimized") self.root.geometry("1400x900") self.root.configure(bg="#f5f5f5") self.root.state('zoomed') # 全屏启动 # === 系统状态 === self.powered_on = False self.current_user = "User" self.clipboard = "" self.notification_log = [] self.open_windows = {} self.showing_app_drawer = False self.taskbar_apps = [] # 当前任务栏运行的应用 # 字体 self.font_ui = ('Segoe UI', 10) self.font_code = ('Consolas', 11) self.font_title = ('Bahnschrift', 14, 'bold') self.font_small = ('Segoe UI', 9) # 文件系统(模拟) self.fs_path = "virtual_fs.json" self.load_filesystem() # 启动动画 self.boot_animation() def load_filesystem(self): if os.path.exists(self.fs_path): try: with open(self.fs_path, 'r', encoding='utf-8') as f: data = json.load(f) self.filesystem = data.get("filesystem", { "/": ["Documents"], "/Documents": [] }) self.file_content = data.get("file_content", {}) self.recycle_bin = data.get("recycle_bin", {}) except: self.init_default_fs() else: self.init_default_fs() def init_default_fs(self): self.filesystem = { "/": ["Documents", "Downloads", "Pictures"], "/Documents": ["readme.txt"], "/Downloads": [], "/Pictures": [] } self.file_content = { "readme.txt": "欢迎使用 AE-OS v9.0\n这是一个可持久化的虚拟系统。" } self.recycle_bin = {} def save_filesystem(self): data = { "filesystem": self.filesystem, "file_content": self.file_content, "recycle_bin": self.recycle_bin } with open(self.fs_path, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) # ======================== # 1. 开机动画(Win12 概念风格) # ======================== def boot_animation(self): splash = tk.Toplevel(self.root) splash.overrideredirect(True) w, h = 600, 350 x = (self.root.winfo_screenwidth() - w) // 2 y = (self.root.winfo_screenheight() - h) // 2 splash.geometry(f"{w}x{h}+{x}+{y}") splash.configure(bg="white") canvas = tk.Canvas(splash, bg="white", highlightthickness=0) canvas.pack(fill=tk.BOTH, expand=True) rings = [] for i in range(4): x0, y0, x1, y1 = 250 + i * 25, 120, 290 + i * 25, 160 ring = canvas.create_oval(x0, y0, x1, y1, outline="#0078d7", width=6) rings.append(ring) label = tk.Label(splash, text="正在启动 Advanced OS v9.0...", fg="gray", bg="white", font=self.font_ui) label.place(relx=0.5, rely=0.7, anchor=tk.CENTER) self.animate_rings(canvas, rings, 0) self.root.after(3500, lambda: self.finish_boot(splash)) def animate_rings(self, canvas, rings, step): colors = ["#0078d7", "#e74856", "#107c10", "#ffb900"] for i in range(4): color = colors[(step + i) % 4] canvas.itemconfig(rings[i], outline=color) if step < 16: self.root.after(200, lambda: self.animate_rings(canvas, rings, step + 1)) def finish_boot(self, splash): splash.destroy() self.powered_on = True self.setup_desktop() # ======================== # 2. 主桌面 # ======================== def setup_desktop(self): self.clear_root() self.root.configure(bg="#f5f5f5") # --- 任务栏 --- taskbar = tk.Frame(self.root, bg="#e8e8e8", height=40) taskbar.pack(side=tk.TOP, fill=tk.X) taskbar.pack_propagate(False) start_btn = round_button(taskbar, "⊞ 开始", self.toggle_app_drawer, bg="#0078d7") start_btn.pack(side=tk.LEFT, padx=10, pady=5) time_label = tk.Label(taskbar, text="", fg="black", bg="#e8e8e8", font=self.font_ui) time_label.pack(side=tk.RIGHT, padx=15) self.update_time(time_label) # 运行中应用区 self.taskbar_apps_frame = tk.Frame(taskbar, bg="#e8e8e8") self.taskbar_apps_frame.pack(side=tk.RIGHT, padx=20) # --- 桌面图标区 --- desktop = tk.Frame(self.root, bg="#f5f5f5") desktop.pack(fill=tk.BOTH, expand=True, padx=40, pady=40) apps = [ ("📄 记事本", self.open_notepad), ("🌐 浏览器", self.open_browser), ("⚙️ 设置", self.open_settings), ("🧮 计算器", self.open_calculator), ("🗑️ 回收站", self.open_recycle_bin), ("📁 文件管理", self.open_file_manager), ("📦 应用商店", self.open_store), ("💬 AI助手", self.open_ai_assistant), ] for name, cmd in apps: self.create_icon(desktop, name, cmd) # --- 状态栏 --- self.status_bar = tk.Label(self.root, text=f"🟢 就绪 | 用户: {self.current_user}", bg="#efefef", fg="gray", font=self.font_small, anchor="w", height=2) self.status_bar.pack(side=tk.BOTTOM, fill=tk.X) self.status_bar.bind("<Button-1>", self.show_notifications) self.add_notification("系统已启动。欢迎使用 AE-OS v9.0") def update_time(self, label): if not self.powered_on: return label.config(text=time.strftime("%H:%M:%S")) self.root.after(1000, lambda: self.update_time(label)) def create_icon(self, parent, text, cmd): frame = tk.Frame(parent, width=100, height=100) frame.pack_propagate(False) frame.pack(side=tk.LEFT, padx=30, pady=30) label = tk.Label(frame, text=text, bg="white", fg="black", font=('Segoe UI Symbol', 10), relief="solid", bd=1, highlightbackground="#ddd", padx=5, pady=5, cursor="hand2") label.pack(fill=tk.BOTH, expand=True) label.bind("<Button-1>", lambda e: cmd() if e.num == 1 else self.show_context_menu(e, text)) label.bind("<Double-Button-1>", lambda e: cmd()) label.bind("<Enter>", lambda e: label.config(bg="#f0f0ff")) label.bind("<Leave>", lambda e: label.config(bg="white")) def show_context_menu(self, event, filename): menu = Menu(self.root, tearoff=0) menu.add_command(label="📋 复制名称", command=lambda: self.copy_text(filename)) menu.tk_popup(event.x_root, event.y_root) # ======================== # 3. 应用抽屉(开始菜单) # ======================== def toggle_app_drawer(self): if self.showing_app_drawer and hasattr(self, 'drawer') and self.drawer.winfo_exists(): self.drawer.destroy() self.showing_app_drawer = False else: self.drawer = tk.Toplevel(self.root) self.drawer.geometry("240x500+10+50") self.drawer.configure(bg="white") self.drawer.overrideredirect(True) self.drawer.attributes('-alpha', 0.98) title = tk.Label(self.drawer, text="📱 所有应用", bg="white", fg="#0078d7", font=self.font_title) title.pack(pady=10) for name, cmd in self.get_all_apps(): btn = round_button(self.drawer, name, cmd, bg="white", fg="black") btn.pack(fill=tk.X, pady=2, padx=10) self.showing_app_drawer = True def get_all_apps(self): return [ ("📄 记事本", self.open_notepad), ("🌐 浏览器", self.open_browser), ("⚙️ 设置", self.open_settings), ("🧮 计算器", self.open_calculator), ("🗑️ 回收站", self.open_recycle_bin), ("📁 文件管理", self.open_file_manager), ("📦 应用商店", self.open_store), ("💬 AI助手", self.open_ai_assistant), ("🔁 重启", self.reboot_system), ("⛔ 关机", self.shutdown_system), ] # ======================== # 4. 通用窗口管理 # ======================== def new_window(self, title, width=800, height=600): win = tk.Toplevel(self.root) win.title(title) win.geometry(f"{width}x{height}") win.configure(bg="white") frame = tk.Frame(win, bg="white", padx=15, pady=15) frame.pack(fill=tk.BOTH, expand=True) # 添加到任务栏 task_btn = round_button(self.taskbar_apps_frame, title.split()[0], lambda: win.lift(), bg="#f0f0f0", fg="black") task_btn.pack(side=tk.LEFT, padx=2) window_id = str(uuid.uuid4()) self.open_windows[window_id] = (win, lambda: self.close_window(window_id, task_btn)) win.protocol("WM_DELETE_WINDOW", lambda: self.close_window(window_id, task_btn)) return window_id, win, frame def close_window(self, wid, task_btn): if wid in self.open_windows: win, _ = self.open_windows[wid] win.destroy() task_btn.destroy() del self.open_windows[wid] # ======================== # 5. 记事本(支持保存) # ======================== def open_notepad(self): wid, win, frame = self.new_window("📄 记事本", 700, 500) text = tk.Text(frame, font=self.font_code, bg="white", fg="black", wrap=tk.WORD) text.pack(fill=tk.BOTH, expand=True) sb = tk.Scrollbar(text, command=text.yview) sb.pack(side=tk.RIGHT, fill=tk.Y) text.config(yscrollcommand=sb.set) menu = Menu(win) menu.add_command(label="💾 保存", command=lambda: self.save_file_dialog(text)) menu.add_command(label="📋 复制", command=lambda: self.copy_from_widget(text)) menu.add_command(label="✂️ 切除", command=lambda: self.cut_from_widget(text)) menu.add_command(label="📌 粘贴", command=lambda: self.paste_to_widget(text)) win.config(menu=menu) def save_file_dialog(self, widget): content = widget.get(1.0, tk.END).strip() fname = filedialog.asksaveasfilename( initialdir="/", title="保存文件", defaultextension=".txt", filetypes=[("Text files", "*.txt"), ("All files", "*.*")] ) if fname: with open(fname, 'w', encoding='utf-8') as f: f.write(content) self.add_notification(f"✅ 已保存到: {os.path.basename(fname)}") # ======================== # 6. 浏览器(带标签页) # ======================== def open_browser(self): wid, win, frame = self.new_window("🌐 浏览器", 900, 600) notebook = tk.Frame(frame, bg="white") notebook.pack(fill=tk.BOTH, expand=True) addr_frame = tk.Frame(notebook, bg="#f0f0f0", height=40) addr_frame.pack(fill=tk.X, pady=5) addr_frame.pack_propagate(False) url_var = tk.StringVar(value="about:start") entry = tk.Entry(addr_frame, textvariable=url_var, font=self.font_code) entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5) go_btn = round_button(addr_frame, "前往", lambda: self.load_page(url_var.get(), text_w), bg="#0078d7") go_btn.pack(side=tk.RIGHT, padx=5) text_w = tk.Text(notebook, bg="white", fg="black", font=self.font_code, wrap=tk.WORD) text_w.pack(fill=tk.BOTH, expand=True) self.load_page("about:start", text_w) def load_page(self, url, text_widget): if url == "about:start": content = "📘 欢迎使用 WinBrowse\n\n- 输入网址浏览\n- 使用 file:// 访问本地文件" elif url.startswith("file://"): fname = url[7:] content = self.file_content.get(fname, "❌ 文件未找到") else: content = f"🌐 正在访问: {url}\n\n此为模拟浏览器,无真实网络连接。" text_widget.config(state=tk.NORMAL) text_widget.delete(1.0, tk.END) text_widget.insert(tk.END, content) text_widget.config(state=tk.DISABLED) # ======================== # 7. 其他应用(略简) # ======================== def open_settings(self): self.simple_app("⚙️ 设置", "系统设置面板") def open_calculator(self): self.simple_app("🧮 计算器", "1+1=2") def open_store(self): self.simple_app("📦 应用商店", "暂无可用应用") def open_ai_assistant(self): self.simple_app("💬 AI助手", "AI 功能需接入模型 API") def simple_app(self, title, content): wid, win, frame = self.new_window(title) tk.Label(frame, text=content, font=self.font_code, fg="gray").pack(pady=20) def open_recycle_bin(self): wid, win, frame = self.new_window("🗑️ 回收站") lb = tk.Listbox(frame, font=self.font_code) lb.pack(fill=tk.BOTH, expand=True) for f in self.recycle_bin: lb.insert(tk.END, f) def open_file_manager(self): wid, win, frame = self.new_window("📁 文件管理器") lb = tk.Listbox(frame, font=self.font_code) lb.pack(fill=tk.BOTH, expand=True) for path, files in self.filesystem.items(): lb.insert(tk.END, f"[{path}]") for f in files: lb.insert(tk.END, f" 📄 {f}") # ======================== # 8. 电源控制 # ======================== def reboot_system(self): self.fade_out() self.root.after(600, self.do_reboot) def do_reboot(self): self.clear_root() self.boot_animation() self.root.after(3500, self.setup_desktop) def shutdown_system(self): self.fade_out() self.root.after(600, self.do_shutdown) def do_shutdown(self): self.save_filesystem() off = tk.Toplevel(self.root) off.overrideredirect(True) off.geometry(f"{self.root.winfo_screenwidth()}x{self.root.winfo_screenheight()}+0+0") off.configure(bg="black") tk.Label(off, text="👋 系统已关闭。你可以安全地关闭计算机。", fg="white", bg="black", font=('Segoe UI', 16)).place(relx=0.5, rely=0.5, anchor=tk.CENTER) self.root.after(3000, self.root.quit) def fade_out(self): for i in range(100, 0, -5): self.root.attributes('-alpha', i / 100) self.root.update() time.sleep(0.02) # ======================== # 9. 工具函数 # ======================== def clear_root(self): for widget in self.root.winfo_children(): widget.destroy() def add_notification(self, msg): t = datetime.now().strftime("%H:%M") self.notification_log.append(f"[{t}] {msg}") if len(self.notification_log) > 100: self.notification_log.pop(0) def show_notifications(self, event): win = tk.Toplevel(self.root) win.title("🔔 通知中心") win.geometry("400x300") win.configure(bg="white") lb = tk.Listbox(win, font=self.font_code, bg="white", fg="black") lb.pack(fill=tk.BOTH, expand=True, padx=10, pady=10) for msg in reversed(self.notification_log[-20:]): lb.insert(0, msg) def copy_from_widget(self, widget): try: selected = widget.get(tk.SEL_FIRST, tk.SEL_LAST) self.clipboard = selected except: pass def cut_from_widget(self, widget): self.copy_from_widget(widget) try: widget.delete(tk.SEL_FIRST, tk.SEL_LAST) except: pass def paste_to_widget(self, widget): if self.clipboard: widget.insert(tk.INSERT, self.clipboard) if __name__ == "__main__": root = tk.Tk() app = Win12UltraVM_Optimized(root) root.mainloop() 简单升级其他应用
最新发布
11-24
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值