向tkinter文本widg添加高级功能

2024-06-29 00:48:26 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我知道tkinter文本小部件可以通过标记机制使用多种字体和颜色,但我不知道如何利用这些功能。

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


Tags: 标记文本功能利用颜色部件tkinter系统
2条回答

1)Tk没有集成的拼写检查器。你可能对PyEnchant感兴趣。

2)3)4)没有那么难(请忘记我之前使用wxPython的建议)。您可以将tag_config作为文本小部件的insert方法的第三个参数传递。它定义此选择的配置。

请参阅以下代码,这些代码改编自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()

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

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

拼写检查也很容易。下面的示例使用/usr/share/dict/words中的单词(这在Windows7上几乎肯定不存在,所以您需要提供一个合适的单词列表),这相当简单,因为它只在您按下空格键时进行拼写检查,但这只是为了将示例的代码大小保持在最小级别。在现实世界中,当你做拼写检查的时候,你会想更聪明一点。

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

相关问题 更多 >