向 tkinter 文本小部件添加高级功能 [英] Add advanced features to a tkinter Text widget

查看:20
本文介绍了向 tkinter 文本小部件添加高级功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个简单的消息传递系统,需要将以下内容添加到 Tkinter 文本小部件:

I am working on a simple messaging system, and need to add the following to a Tkinter text widget:

  1. 拼写检查
  2. 更改字体的选项(在所选文本上)
  3. 更改字体颜色的选项(在所选文本上)
  4. 更改字体大小的选项(在所选文本上)

我了解 tkinter 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.

如何使用文本小部件的功能实现这些功能?具体来说,我如何更改字词的字体系列、颜色和大小,以及如何使用它来实现拼写检查之类的功能,其中拼写错误的字词带有下划线或颜色与文本的其余部分不同.

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.

推荐答案

Tkinter 文本小部件非常强大,但您必须自己实现一些高级功能.它没有内置的拼写检查或用于加粗文本等的内置按钮,但它们很容易实现.所有功能都在小部件中,您只需要知道如何去做.

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.

以下示例为您提供了一个按钮来切换突出显示文本的粗体状态——选择一个字符范围,然后单击该按钮以添加并删除粗体属性.您应该很容易为字体和颜色扩展此示例.

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.

拼写检查也很容易.以下示例使用/usr/share/dict/words 中的单词(Windows 7 上几乎肯定不存在,因此您需要提供合适的单词列表)它相当简单,因为它只进行拼写检查当您按空格键时,但这只是为了将示例的代码大小保持在最低水平.在现实世界中,您需要更聪明地进行拼写检查.

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.

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("
")

    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()

这篇关于向 tkinter 文本小部件添加高级功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆