使用 Python 的 Tkinter 開發記事本


Tkinter 是 Python 的一個 GUI 庫,我們可以用它建立多個 GUI 應用程式。在這裡,我們將使用 Tkinter 開發一個類似記事本的文字編輯器。這個記事本將有一個選單,我們可以用它建立新檔案、開啟現有檔案、儲存檔案、編輯、剪下和貼上,所有功能都將包含在內。

先決條件

  • 已安裝 Python。
  • 已安裝 Tkinter。

注意:Tkinter 作為 Python 3.x 的標準庫提供。

新增選單項

我們的記事本將有四個主要選單項:檔案、編輯、命令和幫助。我們的檔案選單項將有四個子項 - 新建、開啟、儲存和退出。

我們的編輯選單項將有三個子項 - 剪下、複製和貼上

我們的命令選單項將有一個子項 - 關於命令,

我們的幫助選單將有一個子項 - 關於記事本

我們將使用以下程式碼提供這些選單項和子項:

# To open new file
      self.__thisFileMenu.add_command(label="New",
   command=self.__newFile)
      # To open a already existing file
      self.__thisFileMenu.add_command(label="Open",
   command=self.__openFile)
      # To save current file
      self.__thisFileMenu.add_command(label="Save",
   command=self.__saveFile)
      # To create a line in the dialog
      self.__thisFileMenu.add_separator()
      self.__thisFileMenu.add_command(label="Exit",
   command=self.__quitApplication)
      self.__thisMenuBar.add_cascade(label="File", menu=self.__thisFileMenu)
      # To give a feature of cut
      self.__thisEditMenu.add_command(label="Cut",
   command=self.__cut)
      # to give a feature of copy
      self.__thisEditMenu.add_command(label="Copy",
   command=self.__copy)
      # To give a feature of paste
      self.__thisEditMenu.add_command(label="Paste",
   command=self.__paste)
      # To give a feature of editing
      self.__thisMenuBar.add_cascade(label="Edit", menu=self.__thisEditMenu)
      # To create a feature of description of the notepad
      self.__thisHelpMenu.add_command(label="About Notepad",
   command=self.__showAbout)
      self.__thisCommandMenu.add_command(label = "About Commands", command=self.__showCommand)
      self.__thisMenuBar.add_cascade(label="Commands", menu=self.__thisCommandMenu)
      self.__thisMenuBar.add_cascade(label="Help", menu=self.__thisHelpMenu)

為每個選單項新增功能

現在我們已經準備好了選單項,現在我們將為每個選單項新增功能。以下是我們將新增到此記事本的功能列表(當然,您也可以新增更多其他功能)。

  • 開啟檔案
  • 新建檔案
  • 儲存檔案
  • 退出應用程式
  • 顯示關於
  • 顯示命令
  • 剪下
  • 複製
  • 貼上

以下是實現上述功能的程式碼:

def __quitApplication(self):
   self.__root.destroy()
   # exit()
def __showAbout(self):
   showinfo("About Notepad","Simple text editor like notepad using Python")
def __showCommand(self):
   showinfo("Notepad", "Just Another TextPad \n Copyright \n with BSD license you can use it'")
def __openFile(self):
   self.__file = askopenfilename(defaultextension=".txt", filetypes=[("All Files","*.*"),("Text Documents","*.txt")])
   if self.__file == "":
      # no file to open
      self.__file = None
   else:
   # Try to open the file
   # set the window title
   self.__root.title(os.path.basename(self.__file) + " - Notepad")
   self.__thisTextArea.delete(1.0,END)
   file = open(self.__file,"r")
   self.__thisTextArea.insert(1.0,file.read())
   file.close()
def __newFile(self):
   self.__root.title("Untitled Notepad")
   self.__file = None
   self.__thisTextArea.delete(1.0,END)
def __saveFile(self):
   if self.__file == None:
      # Save as new file
   self.__file = asksaveasfilename(initialfile='Untitled.txt', defaultextension=".txt", filetypes=[("All Files","*.*"), ("Text Documents","*.txt")])
   if self.__file == "":
      self.__file = None
   else:
      # Try to save the file
      file = open(self.__file,"w")
      file.write(self.__thisTextArea.get(1.0,END))
      file.close()
      # Change the window title
      self.__root.title(os.path.basename(self.__file) + " - Notepad")
   else:
      file = open(self.__file,"w")
      file.write(self.__thisTextArea.get(1.0,END))
      file.close()
   def __cut(self):
      self.__thisTextArea.event_generate("<<Cut>>")
   def __copy(self):
      self.__thisTextArea.event_generate("<<Copy>>")
   def __paste(self):
      self.__thisTextArea.event_generate("<<Paste>>")

現在我們已經添加了所需的包,添加了一個選單項以及所需的功能,我們將使用 Tkinter 庫在這個類似記事本的文字編輯器中看到這些功能。

以下是使用 Tkinter 建立記事本文字編輯器的完整程式:

#Import os library
import os
#import everything from tkinter
from tkinter import *
#To get the space above the message
from tkinter.messagebox import *
#To get the dialog box to open when required
from tkinter.filedialog import *
class Notepad:
   # Set up the root widget
   __root = Tk()
   __thisWidth = 500
   __thisHeight = 700
   __thisTextArea = Text(__root)
   __thisMenuBar = Menu(__root)
   __thisFileMenu = Menu(__thisMenuBar, tearoff=0)
   __thisEditMenu = Menu(__thisMenuBar, tearoff=0)
   __thisHelpMenu = Menu(__thisMenuBar, tearoff=0)
   __thisCommandMenu = Menu(__thisMenuBar, tearoff=0)
   # To add scrollbar
   __thisScrollBar = Scrollbar(__thisTextArea)
   __file = None
   def __init__(self,**kwargs):
      # icon
      try:
         self.__root.wm_iconbitmap("Notepad.ico")
      except:
         pass
   # Set window size as mentioned above (the default is 300x300)
   try:
      self.__thisWidth = kwargs['width']
      except KeyError:
      pass
   try:
      self.__thisHeight = kwargs['height']
      except KeyError:
      pass
      # the window text
      self.__root.title("Untitled-Notepad")
      # Center the window
      screenWidth = self.__root.winfo_screenwidth()
      screenHeight = self.__root.winfo_screenheight()
      # For left-alling
      left = (screenWidth / 2) - (self.__thisWidth / 2)
      # For right-allign
      top = (screenHeight / 2) - (self.__thisHeight /2)
      # For top and bottom
      self.__root.geometry('%dx%d+%d+%d' % (self.__thisWidth, self.__thisHeight, left, top))
      # To make the textarea auto resizable
      self.__root.grid_rowconfigure(0, weight=1)
      self.__root.grid_columnconfigure(0, weight=1)
      # Add controls (widget)
      self.__thisTextArea.grid(sticky = N + E + S + W)
      # To open new file
      self.__thisFileMenu.add_command(label="New",
   command=self.__newFile)
      # To open a already existing file
      self.__thisFileMenu.add_command(label="Open",
   command=self.__openFile)
      # To save current file
      self.__thisFileMenu.add_command(label="Save",
   command=self.__saveFile)
      # To create a line in the dialog
      self.__thisFileMenu.add_separator()
      self.__thisFileMenu.add_command(label="Exit",
   command=self.__quitApplication)
      self.__thisMenuBar.add_cascade(label="File", menu=self.__thisFileMenu)
      # To give a feature of cut
      self.__thisEditMenu.add_command(label="Cut",
   command=self.__cut)
      # to give a feature of copy
      self.__thisEditMenu.add_command(label="Copy",
   command=self.__copy)
      # To give a feature of paste
      self.__thisEditMenu.add_command(label="Paste",
   command=self.__paste)
      # To give a feature of editing
      self.__thisMenuBar.add_cascade(label="Edit", menu=self.__thisEditMenu)
      # To create a feature of description of the notepad
      self.__thisHelpMenu.add_command(label="About Notepad",
   command=self.__showAbout)
      self.__thisCommandMenu.add_command(label = "About Commands", command=self.__showCommand)
      self.__thisMenuBar.add_cascade(label="Commands", menu=self.__thisCommandMenu)
      self.__thisMenuBar.add_cascade(label="Help", menu=self.__thisHelpMenu)
      self.__root.config(menu=self.__thisMenuBar)
      self.__thisScrollBar.pack(side=RIGHT,fill=Y)
      # Scrollbar will adjust automatically according to the content
      self.__thisScrollBar.config(command=self.__thisTextArea.yview)
      self.__thisTextArea.config(yscrollcommand=self.__thisScrollBar.set)
   def __quitApplication(self):
      self.__root.destroy()
      # exit()
   def __showAbout(self):
      showinfo("About Notepad","Simple text editor like notepad using Python")
   def __showCommand(self):
      showinfo("Notepad", "Just Another TextPad \n Copyright \n with BSD license you can use it'")
   def __openFile(self):
      self.__file = askopenfilename(defaultextension=".txt", filetypes=[("All Files","*.*"),("Text Documents","*.txt")])
      if self.__file == "":
         # no file to open
         self.__file = None
      else:
         # Try to open the file
         # set the window title
         self.__root.title(os.path.basename(self.__file) + " - Notepad")
         self.__thisTextArea.delete(1.0,END)
         file = open(self.__file,"r")
         self.__thisTextArea.insert(1.0,file.read())
         file.close()
   def __newFile(self):
      self.__root.title("Untitled Notepad")
      self.__file = None
      self.__thisTextArea.delete(1.0,END)
   def __saveFile(self):
      if self.__file == None:
         # Save as new file
         self.__file = asksaveasfilename(initialfile='Untitled.txt', defaultextension=".txt", filetypes=[("All Files","*.*"), ("Text Documents","*.txt")])
      if self.__file == "":
         self.__file = None
      else:
         # Try to save the file
         file = open(self.__file,"w")
         file.write(self.__thisTextArea.get(1.0,END))
         file.close()
         # Change the window title
         self.__root.title(os.path.basename(self.__file) + " - Notepad")
      else:
         file = open(self.__file,"w")
         file.write(self.__thisTextArea.get(1.0,END))
         file.close()
   def __cut(self):
      self.__thisTextArea.event_generate("<<Cut>>")
   def __copy(self):
      self.__thisTextArea.event_generate("<<Copy>>")
   def __paste(self):
      self.__thisTextArea.event_generate("<<Paste>>")
   def run(self):
      # Run main application
      self.__root.mainloop()
# Run main application
notepad = Notepad(width=600,height=400)
notepad.run()

執行上述程式後,我們將得到一個彈出式的記事本文字編輯器,類似於

在這個記事本中,我們可以向其中寫入內容,儲存它,並可以開啟我們儲存的檔案(或任何其他檔案)。我們可以從開啟的檔案內容中進行剪下、複製和貼上。您可以使用這個新建立的記事本的所有選單項。

更新於: 2019年7月30日

3K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告