Python implements a simple notepad! This can get two hundred extra money!

Use python to implement a notepad and realize the main functions.

# -*- coding: utf-8 -*-
# @Time    : 2020/10/13
# @Author  : aurora
# @Site    :
# @File    : note.py
# @Version : 1.0
# @Python Version : 3.7
# @Software: PyCharm


from tkinter import *
from tkinter.filedialog import *
from tkinter.messagebox import *
from tkinter import scrolledtext
import them

filename = ''


def author(): # define author function
    showinfo(title="author", message="aurora") # The showinfo() function in the tkinter.messagebox module displays a small graphical user interface (pop-up window) to display text message information


def power(): # define copyright function
    showinfo(title="copyright information", message="copyright belongs to aurora")


def edition():
    showinfo(title="版本号", message="version 1.0")


def new_file(*args): # New file variable length parameters
    global top, filename, textPad # global variables
    top.title("Unnamed File") # The title of the interface is changed from Notepad to Unnamed File
    filename = None # filename
    textPad.delete(1.0, END)   #  ???


def open_file(*args): # open file
    global filename # global variable file name
    filename = askopenfilename(defaultextension=".txt")   #
    if filename == "":
        filename = None
    else:
        top.title("" + os.path.basename(filename)) # system path file name
        textPad.delete(1.0, END)
        f = open(filename,'r', encoding="utf-8") # Open the file and create a new file object f Use the open function to specify the file name operation mode r (default) Write encoding utf-8
        textPad.insert(1.0, f.read())
        f.close() # Close the file object


def click_open(event): # Click to open
    global filename
    top.title("" + os.path.basename(filename)) # Method of calling the system
    textPad.delete(1.0, END)
    f = open(filename, 'r', encoding="utf-8")
    textPad.insert(1.0, f.read()) # read
    f.close()


def save(*args): # save
    global filename
    try:
        f = open(filename, 'w', encoding="utf-8")
        msg = textPad.get(1.0, 'end')
        f.write(msg)
        f.close()
    except:
        save_as() # If you cannot save, execute the save_as function save_as


def save_as(*args): # save as
    global filename
    f = asksaveasfilename(initialfile="未命名.txt", defaultextension=".txt")
    filename = f
    fh = open(f, 'w', encoding="utf-8")
    msg = textPad.get(1.0, END)
    fh.write(msg)
    fh.close()
    top.title("" + os.path.basename(f))


def rename(newname): # System rename function
    global filename
    name = os.path.basename(os.path.splitext(filename)[0])
    oldpath = filename
    newpath = os.path.dirname(oldpath) + '/' + newname + '.txt'
    os.rename(oldpath, newpath)
    filename = newpath
    refresh() # call refresh function


def rename_file(*args): # rename
    global filename
    t = Toplevel()
    t.geometry("260x80+200+250")
    t.title('Rename')
    frame = Frame(t)
    frame.pack(fill=X)
    lable = Label(frame, text="file name")
    lable.pack(side=LEFT, padx=5)
    var = StringVar ()
    e1 = Entry(frame, textvariable=var)
    e1.pack(expand=YES, fill=X, side=RIGHT)
    botton = Button(t, text="确定", command=lambda: rename(var.get()))
    botton.pack(side=BOTTOM, pady=10)


def delete(*args): # delete
    global filename, top
    choice = askokcancel('prompt','do you want to perform this operation')
    if choice:
        if os.path.exists(filename):
            os.remove(filename)
            textPad.delete(1.0, END)
            top.title("Notepad")
            filename = ''


def cut(): # Cut function
    global textPad
    textPad.event_generate("<<Cut>>")


def copy(): # Copy function
    global textPad
    textPad.event_generate("<<Copy>>")


def paste(): # Paste function
    global textPad
    textPad.event_generate("<<Paste>>")


def undo(): # undo
    global textPad
    textPad.event_generate("<<Undo>>")


def redo(): # redo
    global textPad
    textPad.event_generate("<<Redo>>")


def select_all(): # select all
    global textPad
    textPad.tag_add("sel", "1.0", "end")


def find(*agrs): # Find interface above the search bar
    global textPad
    t = Toplevel(top)
    t.title("Find")
    t.geometry("260x60+200+250") # The size of the graphical user interface
    t.transient(top)
    Label(t, text="查找:").grid(row=0, column=0, sticky="e")
    v = StringVar ()
    e = Entry(t, width=20, textvariable=v)
    e.grid(row=0, column=1, padx=2, pady=2, sticky="we")
    e.focus_set()
    c = IntVar ()
    Checkbutton(t, text="case insensitive", variable=c).grid(row=1, column=1, sticky='e')
    Button(t, text="查找所有", command=lambda: search(v.get(), c.get(), textPad, t, e)).grid\
        (row=0, column=2, sticky="e" + "w", padx=2, pady=2) # buttons in the graphical interface

    def close_search(): # Function definition function close search
        textPad.tag_remove("match", "1.0", END)
        t.destroy()

    t.protocol("WM_DELETE_WINDOW", close_search)


def mypopup(event): # popup menu
    global editmenu
    editmenu.tk_popup(event.x_root, event.y_root)


def search(needle, cssnstv, textPad, t, e): # Find and match function inside the article
    textPad.tag_remove("match", "1.0", END)
    count = 0
    if needle:
        start = 1.0
        while True:
            pos = textPad.search(needle, start, nocase=cssnstv, stopindex=END)
            if not pos:
                break
            strlist = pos.split('.') # Split string
            left = strlist[0]
            right = str(int(strlist[1]) + len(needle))
            lastpos = left + '.' + right
            textPad.tag_add("match", pos, lastpos)
            count += 1
            start = lastpos
            textPad.tag_config('match', background="yellow") # The found element becomes a bright yellow highlight
        e.focus_set()
        t.title(str(count) + "one matched") #


def refresh(): # refresh function
    global top, filename
    if filename:
        top.title(os.path.basename(filename))
    else:
        top.title("Notepad")


top = Tk() # New graphical user interface (main interface)
top.title("notepad") # top-level title
top.geometry("640x480+500+200") # Interface size

menubar = Menu(top)

# File function
# Menu class controls are used to implement top-level/drop-down/pop-up menus
filemenu = Menu(top) # Create a top menu
# Add a drop-down submenu through the add_command function
filemenu.add_command(label="New", accelerator="Ctrl+N", command=new_file) # Create a drop-down menu "New", and then add it to the function called after the command binding is clicked in the top menu
filemenu.add_command(label="打开", accelerator="Ctrl+O", command=open_file)
filemenu.add_command(label="保存", accelerator="Ctrl+S", command=save)
filemenu.add_command(label="另存为", accelerator="Ctrl+shift+s", command=save_as)
filemenu.add_command(label="重命名", accelerator="Ctrl+R", command=rename_file)
filemenu.add_command(label="删除", accelerator="Ctrl+D", command=delete)
menubar.add_cascade(label="file(F)", menu=filemenu) # file

# Edit function
editmenu = Menu(top)
editmenu.add_command(label="撤销", accelerator="Ctrl+Z", command=undo)
editmenu.add_command(label="重做", accelerator="Ctrl+Y", command=redo)
editmenu.add_separator() # Separating line
editmenu.add_command(label="剪切", accelerator="Ctrl+X", command=cut)
editmenu.add_command(label="复制", accelerator="Ctrl+C", command=copy)
editmenu.add_command(label="粘贴", accelerator="Ctrl+V", command=paste)
editmenu.add_separator()
editmenu.add_command(label="查找", accelerator="Ctrl+F", command=find)
editmenu.add_command(label="全选", accelerator="Ctrl+A", command=select_all)
menubar.add_cascade(label="Edit(E)", menu=editmenu) # edit

# About function
aboutmenu = Menu(top)
aboutmenu.add_command(label="作者", command=author)
aboutmenu.add_command(label="版权", command=power)
aboutmenu.add_command(label="版本", command=edition)  #
menubar.add_cascade(label="About(A)", menu=aboutmenu) # About

top['menu'] = menubar

shortcutbar = Frame(top, height=25, bg='Silver')
shortcutbar.pack(expand=NO, fill=X)

textPad = Text(top, undo=True)
textPad.pack(expand=YES, fill=BOTH)
scroll = Scrollbar(textPad)
textPad.config(yscrollcommand=scroll.set)
scroll.config(command=textPad.yview)
scroll.pack(side=RIGHT, fill=Y)

# Hotkey binding considers case
textPad.bind("<Control-N>", new_file)
textPad.bind("<Control-n>", new_file)
textPad.bind("<Control-O>", open_file)
textPad.bind("<Control-o>", open_file)
textPad.bind("<Control-S>", save)
textPad.bind("<Control-s>", save)
textPad.bind("<Control-D>", delete)
textPad.bind("<Control-d>", delete)
textPad.bind("<Control-R>", rename_file)
textPad.bind("<Control-r>", rename_file)
textPad.bind("<Control-A>", select_all)
textPad.bind("<Control-a>", select_all)
textPad.bind("<Control-F>", find)
textPad.bind("<Control-f>", find)

textPad.bind("<Button-3>", mypopup)  #
top.mainloop() # Enter the main loop
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274

I usually encounter problems that I ca n’t learn Python, so I can add a communication base ⬅click him

 

Guess you like

Origin blog.csdn.net/weixin_43881394/article/details/109073128