萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python Tkinter 實戰:從零構建簡易文字編輯器

tkinter 是 Python 內建 GUI 框架,零依賴、跨平台。本文完整實作一個具備「開啟、儲存、剪下、貼上、尋找、捲軸、退出確認」功能的文字編輯器,展示 Tkinter 核心元件(Frame、Text、Scrollbar、Menu/Button、對話框)的組合用法。

架構分層

  1. Quitter:封裝「確認退出」按鈕邏輯。
  2. ScrolledText:Text + 垂直 Scrollbar 組合元件,支援載入檔案/字串。
  3. SimpleEditor:繼承 ScrolledText,加上工具列按鈕(儲存、剪下、貼上、尋找、退出)。

核心代碼節錄


class ScrolledText(Frame):
    def __init__(self, parent=None, text='', file=None):
        Frame.__init__(self, parent)
        self.pack(expand=YES, fill=BOTH)
        self.makewidgets()
        self.settext(text, file)

    def makewidgets(self):
        sbar = Scrollbar(self)
        text = Text(self, relief=SUNKEN)
        sbar.config(command=text.yview)
        text.config(yscrollcommand=sbar.set)
        sbar.pack(side=RIGHT, fill=Y)
        text.pack(side=LEFT, expand=YES, fill=BOTH)
        self.text = text

    def settext(self, text='', file=None):
        if file:
            text = open(file, 'r').read()
        self.text.delete('1.0', END)
        self.text.insert('1.0', text)
        self.text.mark_set(INSERT, '1.0')
        self.text.focus()

    def gettext(self):
        return self.text.get('1.0', END+'-1c')  # 去除末尾換行

功能按鈕實作


class SimpleEditor(ScrolledText):
    def __init__(self, parent=None, file=None):
        frm = Frame(parent)
        frm.pack(fill=X)
        Button(frm, text='Save', command=self.onSave).pack(side=LEFT)
        Button(frm, text='Cut', command=self.onCut).pack(side=LEFT)
        Button(frm, text='Paste', command=self.onPaste).pack(side=LEFT)
        Button(frm, text='Find', command=self.onFind).pack(side=LEFT)
        Quitter(frm).pack(side=LEFT)
        ScrolledText.__init__(self, parent, file=file)
        self.text.config(font=('courier', 9, 'normal'))

    def onSave(self):
        filename = asksaveasfilename()
        if filename:
            open(filename, 'w').write(self.gettext())

    def onCut(self):
        text = self.text.get(SEL_FIRST, SEL_LAST)
        self.text.delete(SEL_FIRST, SEL_LAST)
        self.clipboard_clear()
        self.clipboard_append(text)

    def onPaste(self):
        try:
            text = self.selection_get(selection='CLIPBOARD')
            self.text.insert(INSERT, text)
        except TclError:
            pass

    def onFind(self):
        target = askstring('SimpleEditor', 'Search String?')
        if target:
            where = self.text.search(target, INSERT, END)
            if where:
                pastit = where + ('+%dc' % len(target))
                self.text.tag_add(SEL, where, pastit)
                self.text.mark_set(INSERT, pastit)
                self.text.see(INSERT)

啟動入口


if __name__ == '__main__':
    import sys
    try:
        SimpleEditor(file=sys.argv[1]).mainloop()
    except IndexError:
        SimpleEditor().mainloop()

執行畫面

啟動後出現視窗,工具列含「Save/Cut/Paste/Find/Quit」,中央為可編輯文字區,支援捲動。命令列引數可直接載入檔案:python editor.py my.txt。

擴充方向

  • 選單列(Menu)取代工具列按鈕。
  • 語法高亮(Text.tag_config + 正則)。
  • 多標籤(ttk.Notebook)。
  • 撤銷/重做(Text.edit_undo/redo,需 undo=True)。
  • 打包發布:PyInstaller --onefile --windowed editor.py。

不到 100 行代碼構建功能完整的桌面應用,展現了 Tkinter「小而美」的工程價值,適合內部工具、教學示範、輕量級 GUI 需求。

copyright © 萬盛學電腦網 all rights reserved