windows 向 tkinter 文本小部件添加高级功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3732605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add advanced features to a tkinter Text widget
提问by Zac Brown
I am working on a simple messaging system, and need to add the following to a Tkinter text widget:
我正在开发一个简单的消息传递系统,需要将以下内容添加到 Tkinter 文本小部件中:
- Spell Check
- Option To Change Font ( on selected text )
- Option to change font color ( on selected text )
- Option to Change Font Size ( on selected text )
- 拼写检查
- 更改字体的选项(在选定的文本上)
- 更改字体颜色的选项(在所选文本上)
- 更改字体大小的选项(在选定的文本上)
I understand that the tkinter Text widget has the ability to use multiple fonts and colors through the tagging mechanism, but I don't understand how to make use of those capabilities.
我知道 tkinter Text 小部件能够通过标记机制使用多种字体和颜色,但我不明白如何利用这些功能。
How can I implement those features using the features of the Text widget? Specifically, how can I change the font family, color and size of words, and how could I use that to implement something like spellcheck, where misspelled words are underlined or colored differently than the rest of the text.
如何使用文本小部件的功能实现这些功能?具体来说,我如何更改字体系列、单词的颜色和大小,以及如何使用它来实现拼写检查之类的功能,其中拼写错误的单词带有下划线或颜色与文本的其余部分不同。
回答by Bryan Oakley
The Tkinter text widget is remarkably powerful, but you do have to do some advanced features yourself. It doesn't have built-in spell check or built-in buttons for bolding text, etc, but they are quite easy to implement. All the capabilities are there in the widget, you just need to know how to do it.
Tkinter 文本小部件非常强大,但您必须自己做一些高级功能。它没有内置的拼写检查或用于加粗文本等的内置按钮,但它们很容易实现。所有功能都在小部件中,您只需要知道如何去做。
The following example gives you a button to toggle the bold state of the highlighted text -- select a range of characters then click the button to add and then remove the bold attribute. It should be pretty easy for you to extend this example for fonts and colors.
下面的示例为您提供了一个按钮来切换突出显示文本的粗体状态——选择一个字符范围,然后单击该按钮以添加并删除粗体属性。您应该很容易为字体和颜色扩展此示例。
Spell check is also pretty easy. the following example uses the words in /usr/share/dict/words (which almost certainly doesn't exist on Windows 7, so you'll need to supply a suitable list of words) It's rather simplistic in that it only spell-checks when you press the space key, but that's only to keep the code size of the example to a minimal level. In the real world you'll want to be a bit more smart about when you do the spell checking.
拼写检查也很容易。以下示例使用 /usr/share/dict/words 中的单词(Windows 7 上几乎肯定不存在,因此您需要提供合适的单词列表)它相当简单,因为它只进行拼写检查当您按空格键时,但这只是为了将示例的代码大小保持在最低水平。在现实世界中,您会希望在进行拼写检查时更加聪明一些。
import Tkinter as tk
import tkFont
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
## Toolbar
self.toolbar = tk.Frame()
self.bold = tk.Button(name="toolbar", text="bold",
borderwidth=1, command=self.OnBold,)
self.bold.pack(in_=self.toolbar, side="left")
## Main part of the GUI
# I'll use a frame to contain the widget and
# scrollbar; it looks a little nicer that way...
text_frame = tk.Frame(borderwidth=1, relief="sunken")
self.text = tk.Text(wrap="word", background="white",
borderwidth=0, highlightthickness=0)
self.vsb = tk.Scrollbar(orient="vertical", borderwidth=1,
command=self.text.yview)
self.text.configure(yscrollcommand=self.vsb.set)
self.vsb.pack(in_=text_frame,side="right", fill="y", expand=False)
self.text.pack(in_=text_frame, side="left", fill="both", expand=True)
self.toolbar.pack(side="top", fill="x")
text_frame.pack(side="bottom", fill="both", expand=True)
# clone the text widget font and use it as a basis for some
# tags
bold_font = tkFont.Font(self.text, self.text.cget("font"))
bold_font.configure(weight="bold")
self.text.tag_configure("bold", font=bold_font)
self.text.tag_configure("misspelled", foreground="red", underline=True)
# set up a binding to do simple spell check. This merely
# checks the previous word when you type a space. For production
# use you'll need to be a bit more intelligent about when
# to do it.
self.text.bind("<space>", self.Spellcheck)
# initialize the spell checking dictionary. YMMV.
self._words=open("/usr/share/dict/words").read().split("\n")
def Spellcheck(self, event):
'''Spellcheck the word preceeding the insertion point'''
index = self.text.search(r'\s', "insert", backwards=True, regexp=True)
if index == "":
index ="1.0"
else:
index = self.text.index("%s+1c" % index)
word = self.text.get(index, "insert")
if word in self._words:
self.text.tag_remove("misspelled", index, "%s+%dc" % (index, len(word)))
else:
self.text.tag_add("misspelled", index, "%s+%dc" % (index, len(word)))
def OnBold(self):
'''Toggle the bold state of the selected text'''
# toggle the bold state based on the first character
# in the selected range. If bold, unbold it. If not
# bold, bold it.
current_tags = self.text.tag_names("sel.first")
if "bold" in current_tags:
# first char is bold, so unbold the range
self.text.tag_remove("bold", "sel.first", "sel.last")
else:
# first char is normal, so bold the whole selection
self.text.tag_add("bold", "sel.first", "sel.last")
if __name__ == "__main__":
app=App()
app.mainloop()
回答by luc
1) Tk does'nt have an integrated spellchecker. You may be interested by PyEnchant.
1) Tk 没有集成的拼写检查器。您可能对PyEnchant感兴趣。
2) 3) 4) is not that difficult (please forget my previous suggestion to use wxPython). You can pass a tag_config as 3rd arg of the insert method of the text widget. It defines the config of this selection.
2) 3) 4) 并不难(请忘记我之前建议使用 wxPython)。您可以将 tag_config 作为文本小部件的插入方法的第三个参数传递。它定义了这个选择的配置。
See the following code which is adapted from the Scrolledtext example and effbotwhich the best reference about Tk.
请参阅以下改编自 Scrolledtext 示例和effbot 的代码,这是关于 Tk 的最佳参考。
"""
Some text
hello
"""
from Tkinter import *
from Tkconstants import RIGHT, LEFT, Y, BOTH
from tkFont import Font
from ScrolledText import ScrolledText
def example():
import __main__
from Tkconstants import END
stext = ScrolledText(bg='white', height=10)
stext.insert(END, __main__.__doc__)
f = Font(family="times", size=30, weight="bold")
stext.tag_config("font", font=f)
stext.insert(END, "Hello", "font")
stext.pack(fill=BOTH, side=LEFT, expand=True)
stext.focus_set()
stext.mainloop()
if __name__ == "__main__":
example()