溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何用python實(shí)現(xiàn)記事本功能

發(fā)布時(shí)間:2022-01-17 08:56:04 來源:億速云 閱讀:327 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容介紹了“如何用python實(shí)現(xiàn)記事本功能”的有關(guān)知識(shí),在實(shí)際案例的操作過程中,不少人都會(huì)遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

1. 案例介紹

tkinter 是 Python下面向 tk 的圖形界面接口庫,可以方便地進(jìn)行圖形界面設(shè)計(jì)和交互操作編程。tkinter 的優(yōu)點(diǎn)是簡單易用、與 Python 的結(jié)合度好。tkinter 在 Python 3.x 下默認(rèn)集成,不需要額外的安裝操作;不足之處為缺少合適的可視化界面設(shè)計(jì)工具,需要通過代碼來完成窗口設(shè)計(jì)和元素布局。本例采用的 Python 版本為 3.8,如果想在 python 2.x下使用 tkinter,請先進(jìn)行安裝。需要注意的是,不同 Python 版本下的 tkinter 使用方式可能略有不同,建議采用 Python3.x 版本。本例難度為中級(jí),適合具有 Python 基礎(chǔ)和 Tkinter 組件編程知識(shí)的用戶學(xué)習(xí)。

2. 示例效果

如何用python實(shí)現(xiàn)記事本功能

3. 示例源碼

from tkinter import *
from tkinter.filedialog import *
from tkinter.messagebox import *
import os
 
filename = ""
 
 
def author():
    showinfo(title="作者", message="Python")
 
 
def power():
    showinfo(title="版權(quán)信息", message="課堂練習(xí)")
 
 
def mynew():
    global top, filename, textPad
    top.title("未命名文件")
    filename = None
    textPad.delete(1.0, END)
 
 
def myopen():
    global filename
    filename = askopenfilename(defaultextension=".txt")
    if filename == "":
        filename = None
    else:
        top.title("記事本" + os.path.basename(filename))
        textPad.delete(1.0, END)
        f = open(filename, 'r')
        textPad.insert(1.0, f.read())
        f.close()
 
 
def mysave():
    global filename
    try:
        f = open(filename, 'w')
        msg = textPad.get(1.0, 'end')
        f.write(msg)
        f.close()
    except:
        mysaveas()
 
 
def mysaveas():
    global filename
    f = asksaveasfilename(initialfile="未命名.txt", defaultextension=".txt")
    filename = f
    fh = open(f, 'w')
    msg = textPad.get(1.0, END)
    fh.write(msg)
    fh.close()
    top.title("記事本 " + os.path.basename(f))
 
 
def cut():
    global textPad
    textPad.event_generate("<<Cut>>")
 
 
def copy():
    global textPad
    textPad.event_generate("<<Copy>>")
 
 
def paste():
    global textPad
    textPad.event_generate("<<Paste>>")
 
 
def undo():
    global textPad
    textPad.event_generate("<<Undo>>")
 
 
def redo():
    global textPad
    textPad.event_generate("<<Redo>>")
 
 
def select_all():
    global textPad
    # textPad.event_generate("<<Cut>>")
    textPad.tag_add("sel", "1.0", "end")
 
 
def find():
    t = Toplevel(top)
    t.title("查找")
    t.geometry("260x60+200+250")
    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="不區(qū)分大小寫", 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)
 
    def close_search():
        textPad.tag_remove("match", "1.0", END)
        t.destroy()
 
    t.protocol("WM_DELETE_WINDOW", close_search)
 
 
def mypopup(event):
    # global editmenu
    editmenu.tk_popup(event.x_root, event.y_root)
 
 
def search(needle, cssnstv, textPad, t, e):
    textPad.tag_remove("match", "1.0", END)
    count = 0
    if needle:
        pos = "1.0"
        while True:
            pos = textPad.search(needle, pos, nocase=cssnstv, stopindex=END)
            if not pos:
                break
            lastpos = pos + str(len(needle))
            textPad.tag_add("match", pos, lastpos)
            count += 1
            pos = lastpos
        textPad.tag_config('match', fg='yellow', bg="green")
        e.focus_set()
        t.title(str(count) + "個(gè)被匹配")
 
 
top = Tk()
top.title("記事本")
top.geometry("600x400+100+50")
 
menubar = Menu(top)
 
# 文件功能
filemenu = Menu(top)
filemenu.add_command(label="新建", accelerator="Ctrl+N", command=mynew)
filemenu.add_command(label="打開", accelerator="Ctrl+O", command=myopen)
filemenu.add_command(label="保存", accelerator="Ctrl+S", command=mysave)
filemenu.add_command(label="另存為", accelerator="Ctrl+shift+s", command=mysaveas)
menubar.add_cascade(label="文件", menu=filemenu)
 
# 編輯功能
editmenu = Menu(top)
editmenu.add_command(label="撤銷", accelerator="Ctrl+Z", command=undo)
editmenu.add_command(label="重做", accelerator="Ctrl+Y", command=redo)
editmenu.add_separator()
editmenu.add_command(label="剪切", accelerator="Ctrl+X", command=cut)
editmenu.add_command(label="復(fù)制", 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="編輯", menu=editmenu)
 
# 關(guān)于 功能
aboutmenu = Menu(top)
aboutmenu.add_command(label="作者", command=author)
aboutmenu.add_command(label="版權(quán)", command=power)
menubar.add_cascade(label="關(guān)于", menu=aboutmenu)
 
top['menu'] = menubar
 
# shortcutbar = Frame(top, height=25, bg='light sea green')
# shortcutbar.pack(expand=NO, fill=X)
# Inlabe = Label(top, width=2, bg='antique white')
# Inlabe.pack(side=LEFT, anchor='nw', fill=Y)
 
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)
 
# 熱鍵綁定
textPad.bind("<Control-N>", mynew)
textPad.bind("<Control-n>", mynew)
textPad.bind("<Control-O>", myopen)
textPad.bind("<Control-o>", myopen)
textPad.bind("<Control-S>", mysave)
textPad.bind("<Control-s>", mysave)
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()

“如何用python實(shí)現(xiàn)記事本功能”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI