python-2.7 - Python Tkinter 文本编辑器不将字体保存到文本文件

标签 python-2.7 fonts tkinter text-editor rich-text-editor

目前,我正在使用 python 和 tkinter 开发 GUI 文本编辑器。感谢 SO 的伟大人们(谢谢 Rinzler),我成功地修改了文本的字体。但是,我无法将字体和字体大小保存到 txt 文件中。 我知道这应该是可能的,因为记事本可以修改并保存具有指定字体的 txt 文件。

这是保存到文件的代码:

def file_saveas():
    filename = tkFileDialog.asksaveasfile(mode='w', defaultextension=".txt")
    if filename is None: # asksaveasfile return `None` if dialog closed with "cancel".
        return
    text2save = str(textPad.get(1.0, END)) # starts from `1.0`, not `0.0`
    filename.write(text2save)
    filename.close()
    print filename

这是更改字体的代码(由 Rinzler 提供):

def choose_font():
global root, textPad # I hate to use global, but for simplicity

t = Tkinter.Toplevel()
font_name = Tkinter.Label(t, text='Font Name: ')
font_name.grid(row=0, column=0, sticky='nsew')
enter_font = Tkinter.Entry(t)
enter_font.grid(row=0, column=1, sticky='nsew')
font_size = Tkinter.Label(t, text='Font Size: ')
font_size.grid(row=1, column=0, sticky='nsew')
enter_size = Tkinter.Entry(t)
enter_size.grid(row=1, column=1, sticky='nsew')

# associating a lambda with the call to text.config()
# to change the font of text (a Text widget reference)
ok_btn = Tkinter.Button(t, text='Apply Changes',
                   command=lambda: textPad.config(font=(enter_font.get(), 
                   enter_size.get())))
print font
ok_btn.grid(row=2, column=1, sticky='nsew')
done = Tkinter.Button(t, text='Get rid of Pushy!', command=t.destroy)
done.grid(row=4, column=1, sticky='nsew')
# just to make strechable widgets
# you don't strictly need this
for i in range(2):
    t.grid_rowconfigure(i, weight=1)
    t.grid_columnconfigure(i, weight=1)
t.grid_rowconfigure(2, weight=1)

最后,这是读取字体和其他配置信息的代码:

font = (fontname, size)
textPad.config(
    borderwidth=0,
    font=font ,
    foreground="green",
    background="black",
    insertbackground="white", # cursor
    selectforeground="blue", # selection
    selectbackground="#008000",
    wrap="word", 
    width=64,
    undo=True, # Tk 8.4
    )

我在互联网上搜索过,但没有找到任何关于为什么不保存字体和文本大小的答案。任何帮助将不胜感激。

我正在使用 python 2.7.7 、Tkinter,并且它在 Windows 7 上运行。

任何操作 rtf 文件的帮助也会有所帮助(目前,我看到标签而不是最终格式)。

最佳答案

tkinter 中不支持此操作。您必须选择支持字体的文件格式(rtf、.docx、.html 等),将小部件中的数据转换为该格式,然后将其写入文件。

关于python-2.7 - Python Tkinter 文本编辑器不将字体保存到文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28376584/

相关文章:

python - 如何停止打印播放功能?

android - 是否可以更改 Android 模拟器字体?

Python:Matplotlib:如何在其中打印不同大小的一个文本?

CSS mask-image 不工作(试过 firefox 和 safari)

python - 格式化 tkinter 文本框

Python Tkinter Text Widget .get 方法错误

windows - 在 Windows 上运行 'docker-compose up' 会引发 "No module named fnctl"错误

python-2.7 - 在 Python turtle Canvas 上更改 Canvas 滚动区域

python-3.x - 如何从 TinyDB 数据库中检索单个值?

mysql - 带断线的 django + mysql 文本字段格式