python实现markdown编辑器-7

python实现markdown编辑器

  • 前言
  • 开始
      • KaTeX \KaTeX KATEX公式

前言

开始

KaTeX \KaTeX KATEX公式

# 1号标题
## 2号标题
### 3号标题
#### 4号标题
##### 5号标题
###### 6号标题
- 无序列表第一种
* 无序列表第二种
+ 无序列表第三种
1. test
2. test
3. test
- [ ] unchecked
- [x] checked
` ` `
import this
` ` `
test
: test1
: test2
$$\sin x$$

行内 KaTeX \KaTeX KATEX也放在最后。
看一个 sin ⁡ x \sin x sinx图片

图片url:https://latex.codecogs.com/png.image?\dpi{110}%20\sin%20x,去掉HTML转义之后就是https://latex.codecogs.com/png.image?\dpi{110} \sin x
对,你没看错,每个公式的url就是"https://latex.codecogs.com/png.image?\dpi{110} "+这个公式。
下面给出一段tkinter显示 sin ⁡ x \sin x sinx的示例:

from PIL import Image,ImageTk
import tkinter as tk
import requests
import io
def get_KaTeX_io(katex):
	resp = requests.get('https://latex.codecogs.com/png.image?\dpi{110} ' + katex)
	return io.BytesIO(resp.content)
def get_KaTeX(katex):
	img_io = get_KaTeX_io(katex)
	img = Image.open(img_io)
	return ImageTk.PhotoImage(img)
if(__name__ == '__main__'):
	base = tk.Tk()
	imgTk = get_KaTeX(r'\sin x')
	label = tk.Label(base,image=imgTk)
	label.pack()
	base.mainloop()

但是,请注意,一下代码是无法正常显示的:

from PIL import Image,ImageTk
import tkinter as tk
import requests
import io
def get_KaTeX_io(katex):
	resp = requests.get('https://latex.codecogs.com/png.image?\dpi{110} ' + katex)
	return io.BytesIO(resp.content)
def get_KaTeX(katex):
	img_io = get_KaTeX_io(katex)
	img = Image.open(img_io)
	return ImageTk.PhotoImage(img)
def KaTeX(base,katex):
	imgTk = get_KaTeX(katex)
	label = tk.Label(base,image=imgTk)
	label.pack()
if(__name__ == '__main__'):
	base = tk.Tk()
	KaTeX(base,r'\sin x')
	base.mainloop()

这是因为在函数执行完成后imgTk这个变量的引用数降为零,gc将其回收,所以可以通过控制引用数不降为零的方式解决:

from PIL import Image,ImageTk
import tkinter as tk
import requests
import io
def get_KaTeX_io(katex):
	resp = requests.get('https://latex.codecogs.com/png.image?\dpi{110} ' + katex)
	return io.BytesIO(resp.content)
def get_KaTeX(katex):
	img_io = get_KaTeX_io(katex)
	img = Image.open(img_io)
	return ImageTk.PhotoImage(img)
def KaTeX(base,katex):
	imgTk = get_KaTeX(katex)
	label = tk.Label(base,image=imgTk)
	label.image = imgTk
	label.pack()
if(__name__ == '__main__'):
	base = tk.Tk()
	KaTeX(base,r'\sin x')
	base.mainloop()

即可
所以得出代码:

from tkinter.filedialog import askopenfilename as aof,asksaveasfilename as asf
from tkinter.messagebox import askyesno as askyn
from PIL import Image,ImageTk
from tkinter import ttk
import tkinter as tk
import requests
import io
fontname = ...
display = tk.Tk()
writer = tk.Toplevel()
widgets = []
text = tk.Text(writer)
text.grid(row=0,column=0)
cont = ''
def read_md(file):
 	with open(file) as f:
 			return f.read()
def write_md(file,cont):
 	with open(file,'w') as f:
 		f.write(cont)
def clear():
	for i in widgets:
		i.grid_forget()
def get_KaTeX_io(katex):
	resp = requests.get('https://latex.codecogs.com/png.image?\dpi{110} ' + katex)
	return io.BytesIO(resp.content)
def get_KaTeX(katex):
	img_io = get_KaTeX_io(katex)
	img = Image.open(img_io)
	return ImageTk.PhotoImage(img)
def render_md():
	display.update()
	clear()
	l = 0
	code = False
	buf = ''
	for i in cont.split('\n'):
		if(code and i != '```'):
			buf += i + '\n'
			continue
		if(i.startswith('# ')):
			lb = tk.Label(display,text=i[2:],font=(fontname,40,'bold'))
		elif(i.startswith('## ')):
			lb = tk.Label(display,text=i[3:],font=(fontname,35,'bold'))
		elif(i.startswith('### ')):
			lb = tk.Label(display,text=i[4:],font=(fontname,30,'bold'))
		elif(i.startswith('#### ')):
			lb = tk.Label(display,text=i[5:],font=(fontname,25,'bold'))
		elif(i.startswith('##### ')):
			lb = tk.Label(display,text=i[6:],font=(fontname,20,'bold'))
		elif(i.startswith('###### ')):
			lb = tk.Label(display,text=i[7:],font=(fontname,15,'bold'))
		elif(i.startswith('- [ ] ')):
			lb = tk.Checkbutton(display,text=i[6:],state=tk.DISABLED)
		elif(i.startswith('- [x] ')):
			lb = tk.Checkbutton(display,text=i[6:],state=tk.DISABLED)
			lb.select()
		elif(i.startswith('- ') or i.startswith('* ') or i.startswith('+ ')):
			i = '● ' + i[2:]
			lb = tk.Label(display,text=i,font=(fontname,15,''))
		elif(i.startswith(': ')):
			lb = tk.Label(display,text='\t'+i[2:])
		elif(i.startswith('$$') and i.endswith('$$') and i not in ('$$','$$$')):
			imgTk = get_KaTeX(i[2:-2])
			lb = tk.Label(display,image=imgTk)
			lb.image = imgTk
			lb.grid(row=l,column=0,sticky='c')
			l += 1
			continue
		elif(i == '```'):
			if(code):
				lb = tk.Text(display)
				lb.insert(0.0,buf)
				h = float(lb.index(tk.END)) - 2
				lb.config(height=h)
				buf = ''
				code = False
			else:
				code = True
				continue
		else:
			lb = tk.Label(display,text=i,font=(fontname,15,''))
		lb.grid(row=l,column=0)
		widgets.append(lb)
		l += 1
def update_writer():
	global cont
	writer.update()
	cont = text.get(0.0,tk.END)
def main():
	global cont
	writer.title('writer')
	display.title('displayer')
	file = aof(title='open a markdown file')
	if(file):
		cont = read_md(file)
	text.insert(0.0,cont)
	while(1):
		try:
			update_writer()
			render_md()
		except:

			try:
				writer.destroy()
			except:
				pass
			try:
				display.destroy()
			except:
				pass
			tk.Tk().withdraw()
			if(file):
				write_md(file,cont)
			else:
				while(1):
					file = asf(title='save as ...')
					if(not file):
						if(not askyn('Do you want to keep this new document?','Do you want to keep this new document?')):
							exit()
					write_md(file)
if(__name__ == '__main__'):
	main()

效果:python实现markdown编辑器-7_第1张图片

>> 《python实现markdown编辑器-8》

你可能感兴趣的:(python,markdown)