from tkinter import *
from tkinter.filedialog import asksaveasfilename, askopenfilename
current_file = None
def new_file():
global current_file
current_file = None
text.delete(1.0, END)
def open_file():
global current_file
filepath = askopenfilename(defaultextension='.txt',
filetypes=[('Text Files', '*.txt'),
('All Files', '*.*')])
if not filepath:
return
current_file = filepath
text.delete(1.0, END)
with open(filepath, 'r') as file:
text.insert(INSERT, file.read())
def save_file():
global current_file
if not current_file:
filepath = asksaveasfilename(defaultextension='.txt',
filetypes=[('Text Files', '*.txt'),
('All Files', '*.*')])
if not filepath:
return
current_file = filepath
with open(current_file, 'w') as file:
file.write(text.get(1.0, END))
def exit_app():
root.quit()
def undo():
text.edit_undo()
def redo():
text.edit_redo()
root = Tk()
root.title('Notepad')
menu_bar = Menu(root)
root.config(menu=menu_bar)
file_menu = Menu(menu_bar, tearoff=False)
menu_bar.add_cascade(label='File', menu=file_menu)
file_menu.add_command(label='New', command=new_file)
file_menu.add_command(label='Open', command=open_file)
file_menu.add_command(label='Save', command=save_file)
file_menu.add_separator()
file_menu.add_command(label='Exit', command=exit_app)
edit_menu = Menu(menu_bar, tearoff=False)
menu_bar.add_cascade(label='Edit', menu=edit_menu)
edit_menu.add_command(label='Undo', command=undo)
edit_menu.add_command(label='Redo', command=redo)
text = Text(root)
text.pack(expand=True, fill=BOTH)
toolbar = Frame(root, bd=1, relief=RAISED)
undo_btn = Button(toolbar, text='Undo', command=undo)
undo_btn.pack(side=LEFT, padx=2, pady=2)
redo_btn = Button(toolbar, text='Redo', command=redo)
redo_btn.pack(side=LEFT, padx=2, pady=2)
toolbar.pack(side=TOP, fill=X)
root.mainloop()
This code creates a simple notepad app using the Tkinter library in Python. The app has a menu bar with options to create a new file, open an existing file, and save the current file. The text area of the app is implemented using a Text widget. The app supports both saving and opening files in the .txt format.