How to build a Markdown editor in Python

王林
Release: 2023-05-13 09:58:05
forward
1461 people have browsed it

First, make sure you have Python 3 and Tkinter installed.

The other things we need are tkhtmlview and markdown2. You can install them by running pip install tkhtmlview markdown2 or pip3 install tkhtmlview markdown2 (if you have multiple Python versions).

Now launch your favorite editor or IDE and create a new file (for example www.linuxidc.com.py (I named it linuxidc.com editor)).

We will start by importing the necessary libraries.

from tkinter import *  from tkinter import font , filedialog  from markdown2 import Markdown  from tkhtmlview import HTMLLabel
Copy after login

In the first line, we import (almost) everything from the tkinter package.

In the second line, we import the font and file dialog. Font is needed to style the input fields (e.g. Font, Font Size) and imported filedialog to open the markdown file for editing (and/or save our markdown file).

In the third line, Markdown is imported to help us convert the Markdown source to html and display it in the output field using HTMLLabel (imported in the fourth line).

After that, we will create a frame class called Window, which will inherit from tkinters’ Frame class. It will hold our input and output fields.

class Window(Frame):      def __init__(self, master=None):          Frame.__init__(self, master)          self.master = master          self.myfont = font.Font(family="Helvetica", size=14)          self.init_window()      def init_window(self):          self.master.title("linuxidc.com编辑器")          self.pack(fill=BOTH, expand=1)
Copy after login

In this code block, we first define a class called Window, which inherits tkinter’s Frame widget class.

Now, in the initialization function, we pass master as a parameter to be used as the parent of the frame. In the next line, we initialize a Frame.

Next, we declare a custom font object called self.myfont with font family Helvetica (you can choose any font family) and size 15 that will be used in our markdown input field .

Finally, we call the init_window function to put our application at the core.

In the init_window function, we first set the title of the window to linuxidc.com editor. In the next line, self.pack(fill=BOTH, expand=1), we tell Frame to take up the full space of the window.

We set the fill keyword argument to BOTH, which is actually imported from the tkinter library. It tells the frame to fill the window both horizontally and vertically, and the expand keyword argument is set to 1 (meaning True), which tells us that the frame is expandable. In short, no matter how we stretch the window size or maximize the window size, the frame will fill the window.

Now if you run the www.linuxidc.com.py script you won't see anything because we only defined the class but never called it.

To solve this problem, we put the following code at the end of the script:

root = Tk()  root.geometry("800x600")  app = Window(root)  app.mainloop()
Copy after login

Next, set the geometry of the window to a cuboid of 800x600, 800 is the height of the window, and 600 is The width of the window. In the next line you can see we are creating a Window object. We push the root variable into the root of the framework and store it in a variable called app.

The next thing to do is call the mainloop function, which tells our application to run!

Now run the www.linuxidc.com.py script. If you've done everything correctly, you'll see a blank window that looks like this:

How to build a Markdown editor in Python

But it's just a blank window. To write content in the window, we need to add a text field in which to write our markdown. For this we will use the Text widget from tkinter.

...  def init_window(self):      self.master.title("linuxidc.com编辑器")      self.pack(fill=BOTH, expand=1)      self.inputeditor = Text(self, width="1")      self.inputeditor.pack(fill=BOTH, expand=1, side=LEFT)
Copy after login

Not to be confused with (three dots), I put them there just to indicate that there are multiple lines of code before this block of code.

Here, we create a Text widget with a width of 1. Don't get the wrong idea - the sizing here is done using proportions. You'll get a better idea of ​​it in the next few seconds when we put it into the output box.

We then wrap it into a frame and make it stretchable both horizontally and vertically.

When you run the script, you will see that the entire "window" has been taken over. If you start writing it, you may notice that the characters are too small.

I already knew this problem would occur. This is why I told you before to create a custom font object (self.myfont). Now, if you do the following:

self.inputeditor = Text(self, width="1" , font=self.myfont)
Copy after login

(Here, we tell the Text widget to use a custom font instead of the default small font!)

...the font size of the input field will be increased to 15. Run the script to check if everything is OK.

How to build a Markdown editor in Python

Now, I think it's time to add the outputbox, we will see the html output of the markdown source code as we write.

To do this, we need to add an HTMLLabel, which looks like this in the init_window function:

self.outputbox = HTMLLabel(self, width="1", background="white", html="<h2>linuxidc.com</h2>")  self.outputbox.pack(fill=BOTH, expand=1, side=RIGHT)  self.outputbox.fit_height()
Copy after login

We use the HTMLLabel in tkhtmlview, and the width is still 1. We set the width to 1 because the window will be shared 1:1 between the input field and the output box (you'll see what I mean when you run the script).

htmlKeyword parameters store the value that will be displayed the first time.

然后,将其打包在窗口中,将side作为RIGHT置于输入字段的右侧。fit_height()使文本适合小部件。

现在运行代码,如下所示:

How to build a Markdown editor in Python

现在,如果您开始在输入字段中书写,输入时输出不会得到更新。那是因为我们还没有告诉我们的程序这样做。

为此,我们首先要与编辑器绑定一个事件。然后,你进行修改文本,输出都会得到更新,如下所示:

self.inputeditor.bind(">", self.onInputChange)
Copy after login

将这一行放到init_window()函数中。

这一行告诉inputeditor在文本改变时调用onInputChange函数。但是因为我们还没有那个函数,我们需要把它写出来。

...  def onInputChange(self , event):      self.inputeditor.edit_modified(0)      md2html = Markdown()      self.outputbox.set_html(md2html.convert(self.inputeditor.get("1.0" , END)))
Copy after login

在第一行中,我们使用edit_modified(0)重置修改后的标志,以便重用它。否则,在第一次事件调用之后,它将不再工作。

接下来,我们创建一个名为md2html的Markdown对象。最后一行(上面标红那行),首先我们…等等!最后一行可能会让一些读者感到困惑。我把它分成三行。

markdownText = self.inputeditor.get("1.0" , END)  html = md2html.convert(markdownText)  self.outputbox.set_html(html)
Copy after login

在第一行中,我们从输入字段的顶部到底部获取markdown文本。第一个参数,self.inputeditor.get,告诉它从第一行的第0个字符开始扫描(1.0 => [LINE_NUMBER].[CHARACTER_NUMBER]),最后一个参数告诉它在到达末尾时停止扫描。

然后,我们使用md2html.convert()函数将扫描的markdown文本转换为html,并将其存储在html变量中。

最后,我们告诉outputbox使用.set_html()函数来显示输出!

运行脚本。您将看到一个功能几乎正常的markdown编辑器。当您输入输入字段时,输出也将被更新。

但是…我们的工作还没有完成。用户至少需要能够打开和保存他们的文本。

为此,我们要在菜单栏中添加一个文件菜单。在这里,用户可以打开和保存文件,也可以退出应用程序。

在init_window函数中,我们将添加以下行:

self.mainmenu = Menu(self)  self.filemenu = Menu(self.mainmenu)  self.filemenu.add_command(label="打开", command=self.openfile)  self.filemenu.add_command(label="另存为", command=self.savefile)  self.filemenu.add_separator()  self.filemenu.add_command(label="退出", command=self.quit)  self.mainmenu.add_cascade(label="文件", menu=self.filemenu)  self.master.config(menu=self.mainmenu)
Copy after login

简单说一下:

在这里,我们定义了一个新菜单,框架作为它的父菜单。

接下来,我们定义另一个菜单和上一个菜单作为其父菜单。它将作为我们的文件菜单。

然后使用add_command()和add_separator()函数添加3个子菜单(打开、另存为和退出)和分隔符。打开子菜单将执行openfile函数,另存为子菜单将执行savefile函数。最后,Exit将执行一个内建函数quit,该函数将关闭程序。

然后使用add_cascade()函数告诉第一个菜单对象包含filemenu变量。这包括标签文件中的所有子菜单。

最后,我们使用self.master.config()来告诉窗口使用主菜单作为窗口的菜单栏。

它看起来是这样的,但是现在还不要运行它。你会提示错误,openfile和savefile函数没有定义。

正如您现在看到的,我们必须在Window类中定义两个函数,我们将在其中使用tkinter的filedialog。

首先让我们定义打开文件的函数:

def openfile(self):      openfilename = filedialog.askopenfilename(filetypes=(("Markdown File", "*.md , *.mdown , *.markdown"),                                                                    ("Text File", "*.txt"),                                                                    ("All Files", "*.*")))      if openfilename:          try:              self.inputeditor.delete(1.0, END)              self.inputeditor.insert(END , open(openfilename).read())          except:              print("无法打开文件!")
Copy after login

在这里,首先我们向用户显示一个文件浏览器对话框,允许他们使用filedialog.askopenfilename()选择要打开的文件。与filetypes关键字参数,我们告诉对话框只打开这些类型的文件通过传递一个元组与支持的文件(基本上所有类型的文件):

  •  带 .md , .mdown , .markdown扩展名的文件

  •  扩展名为.txt的文本文件

  •  在使用通配符扩展的下一行中,我们告诉对话框打开任何扩展名的文件。

然后我们检查用户是否选择了一个文件。如果是,我们尝试打开文件。然后删除输入字段中从第一行的第0个字符到字段末尾的所有文本。

接下来,我们打开并读取所选文件的内容,并在输入字段中插入内容。

如果我们的程序不能打开一个文件,它将打印出错误。但是等等,这不是处理错误的好方法。我们在这里可以做的是向用户显示一个类似这样的错误消息:

How to build a Markdown editor in Python

为此,我们首先要从tkinter包中导入消息框messagebox。

from tkinter import messagebox as mbox
Copy after login

然后,不像上面那样只是打印一个错误消息,我们将用下面的行替换那一行,以便向用户显示正确的错误消息。

mbox.showerror(“打开选定文件时出错 " , "哎呀!,您选择的文件:{}无法打开!".format(openfilename))

这将创建一个错误消息,就像我上面显示的文件无法打开时的屏幕截图一样。

mbox.showerror函数,第一个参数是消息框的标题。第二个是要显示的消息。

现在,我们需要编写一个savefile函数来保存markdown输入。

def savefile(self):          filedata = self.inputeditor.get("1.0" , END)          savefilename = filedialog.asksaveasfilename(filetypes = (("Markdown File", "*.md"),                                                                    ("Text File", "*.txt")) , title="保存 Markdown 文件")          if savefilename:              try:                  f = open(savefilename , "w")                  f.write(filedata)              except:                  mbox.showerror("保存文件错误" , "哎呀!, 文件: {} 保存错误!".format(savefilename))
Copy after login

在这里,首先我们扫描输入字段的所有内容并将其存储在一个变量中。然后,我们通过为两种类型的文件类型(.md和.txt)。

如果用户选择一个文件名,我们将尝试保存存储在变量filedata中的输入字段的内容。如果发生异常,我们将向用户显示一条错误消息,说明程序无法保存文件。

The above is the detailed content of How to build a Markdown editor in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template