目前,我正在使用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等)的文件格式,然后将小部件中的数据转换为这种格式,然后将其写入文件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句