Tkinter là thư viện GUI chuẩn của Python. Bài viết hướng dẫn xây dựng Notepad đơn giản: tạo file, mở file, lưu file, cắt/copy/paste, menu Help/About.
Yêu cầu
- Python 3.x (Tkinter có sẵn)
Cấu trúc Menu
- File: New, Open, Save, Exit
- Edit: Cut, Copy, Paste
- Commands: About Commands
- Help: About Notepad
Thêm menu vào giao diện
# File menu self.__thisFileMenu.add_command(label="New", command=self.__newFile) self.__thisFileMenu.add_command(label="Open", command=self.__openFile) self.__thisFileMenu.add_command(label="Save", command=self.__saveFile) self.__thisFileMenu.add_separator() self.__thisFileMenu.add_command(label="Exit", command=self.__quitApplication) self.__thisMenuBar.add_cascade(label="File", menu=self.__thisFileMenu) # Edit menu self.__thisEditMenu.add_command(label="Cut", command=self.__cut) self.__thisEditMenu.add_command(label="Copy", command=self.__copy) self.__thisEditMenu.add_command(label="Paste", command=self.__paste) self.__thisMenuBar.add_cascade(label="Edit", menu=self.__thisEditMenu) # Commands & Help self.__thisHelpMenu.add_command(label="About Notepad", command=self.__showAbout) self.__thisCommandMenu.add_command(label="About Commands", command=self.__showCommand) self.__thisMenuBar.add_cascade(label="Commands", menu=self.__thisCommandMenu) self.__thisMenuBar.add_cascade(label="Help", menu=self.__thisHelpMenu) self.__root.config(menu=self.__thisMenuBar)
Chức năng các mục menu
def __quitApplication(self):
self.__root.destroy()
def __showAbout(self):
showinfo("About Notepad", "Simple text editor like notepad using Python")
def __showCommand(self):
showinfo("Notepad", "Just Another TextPad\nCopyright\nBSD license")
def __openFile(self):
self.__file = askopenfilename(
defaultextension=".txt",
filetypes=[("All Files", "*.*"), ("Text Documents", "*.txt")]
)
if self.__file:
self.__root.title(os.path.basename(self.__file) + " - Notepad")
self.__thisTextArea.delete(1.0, END)
with open(self.__file, "r") as f:
self.__thisTextArea.insert(1.0, f.read())
def __newFile(self):
self.__root.title("Untitled Notepad")
self.__file = None
self.__thisTextArea.delete(1.0, END)
def __saveFile(self):
if self.__file is None:
self.__file = asksaveasfilename(
initialfile='Untitled.txt',
defaultextension=".txt",
filetypes=[("All Files", "*.*"), ("Text Documents", "*.txt")]
)
if self.__file:
with open(self.__file, "w") as f:
f.write(self.__thisTextArea.get(1.0, END))
self.__root.title(os.path.basename(self.__file) + " - Notepad")
def __cut(self):
self.__thisTextArea.event_generate("<>")
def __copy(self):
self.__thisTextArea.event_generate("<>")
def __paste(self):
self.__thisTextArea.event_generate("<>")
Chương trình hoàn chỉnh
import os
from tkinter import *
from tkinter.messagebox import *
from tkinter.filedialog import *
class Notepad:
__root = Tk()
__thisWidth = 500
__thisHeight = 700
__thisTextArea = Text(__root)
__thisMenuBar = Menu(__root)
__thisFileMenu = Menu(__thisMenuBar, tearoff=0)
__thisEditMenu = Menu(__thisMenuBar, tearoff=0)
__thisHelpMenu = Menu(__thisMenuBar, tearoff=0)
__thisCommandMenu = Menu(__thisMenuBar, tearoff=0)
__thisScrollBar = Scrollbar(__thisTextArea)
__file = None
def __init__(self, **kwargs):
try:
self.__root.wm_iconbitmap("Notepad.ico")
except:
pass
try: self.__thisWidth = kwargs['width']
except KeyError: pass
try: self.__thisHeight = kwargs['height']
except KeyError: pass
self.__root.title("Untitled-Notepad")
# Căn giữa màn hình
screenWidth = self.__root.winfo_screenwidth()
screenHeight = self.__root.winfo_screenheight()
left = (screenWidth / 2) - (self.__thisWidth / 2)
top = (screenHeight / 2) - (self.__thisHeight / 2)
self.__root.geometry('%dx%d+%d+%d' % (self.__thisWidth, self.__thisHeight, left, top))
# Text area tự co giãn
self.__root.grid_rowconfigure(0, weight=1)
self.__root.grid_columnconfigure(0, weight=1)
self.__thisTextArea.grid(sticky=N+E+S+W)
# ... (Thêm menu như phần trên)
# ... (Scrollbar)
self.__thisScrollBar.pack(side=RIGHT, fill=Y)
self.__thisScrollBar.config(command=self.__thisTextArea.yview)
self.__thisTextArea.config(yscrollcommand=self.__thisScrollBar.set)
# ... (Các phương thức __quitApplication, __showAbout, __openFile, v.v.)
def run(self):
self.__root.mainloop()
# Chạy ứng dụng
notepad = Notepad(width=600, height=400)
notepad.run()
Kết quả
Cửa sổ Notepad hiện ra với đầy đủ menu, thanh cuộn, khu vực soạn thảo. Có thể soạn thảo, lưu, mở file .txt.