python GUI开发: tkinter菜单创建,记事本和画图软件综合项目的实战演练
import tkinter as tk
from tkinter import filedialog, messagebox
class SimpleNotepad(tk.Tk):
def __init__(self):
super().__init__()
self.title("Simple Notepad")
self.filename = None
self.text_editor = tk.Text(self)
self.text_editor.pack(expand=True, fill=tk.BOTH)
self.create_menu()
def create_menu(self):
menu_bar = tk.Menu(self)
file_menu = tk.Menu(menu_bar, tearoff=False)
file_menu.add_command(label="Open", command=self.on_open)
file_menu.add_command(label="Save", command=self.on_save)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=self.on_exit)
menu_bar.add_cascade(label="File", menu=file_menu)
self.config(menu=menu_bar)
def on_open(self):
self.filename = filedialog.askopenfilename(initialdir="./", title="Select a File", filetypes=(("Text Files", "*.txt"), ("All Files", "*.*")))
if self.filename:
with open(self.filename, "r") as file:
self.text_editor.delete("1.0", tk.END)
self.text_editor.insert(tk.END, file.read())
self.title(f"{self.filename} - Simple Notepad")
def on_save(self):
if self.filename:
with open(self.filename, "w") as file:
file.write(self.text_editor.get("1.0", tk.END))
else:
self.on_save_as()
def on_save_as(self):
filename = filedialog.asksaveasfilename(initialdir="./", title="Save As", filetypes=(("Text Files", "*.txt"), ("All Files", "*.*")))
if filename:
with open(filename, "w") as file:
file.write(self.text_editor.get("1.0", tk.END))
self.filename = filename
self.title(f"{self.filename} - Simple Notepad")
def on_exit(self):
if messagebox.askokcancel("Quit", "Do you want to quit?"):
self.destroy()
if __name__ == "__main__":
app = SimpleNotepad()
app.mainloop()
这段代码实现了一个简单的记事本应用程序,使用了tkinter库来创建GUI界面,并实现了文件的打开、保存和退出功能。代码简洁,注释清晰,是学习GUI编程和文件操作的良好示例。
评论已关闭