Текстовый виджет Tkinter замечательно мощный, но вам нужно сделать некоторые дополнительные функции самостоятельно. Он не имеет встроенной проверки орфографии или встроенных кнопок для полужирного текста и т. Д., Но их довольно просто реализовать. Все возможности присутствуют в виджетах, вам просто нужно знать, как это сделать.
Следующий пример дает вам кнопку для переключения жирного состояния выделенного текста - выберите диапазон символов, затем нажмите кнопку, чтобы добавить, а затем удалите жирный атрибут. Для вас достаточно просто расширить этот пример для шрифтов и цветов.
Проверка орфографии также довольно проста. в следующем примере используются слова в/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()
Вопрос сейчас, похоже, не запрашивает резус-источник, а скорее реализацию, так как все остальные вопросы также относятся к SO. – Trilarion
Я озадачен закрытием из-за отсутствия темы. Это не просит помочь найти ресурс или инструмент как таковой, он спрашивает, как что-то можно реализовать. По общему признанию, он немного широк, но принятый ответ не связан с внешними инструментами или библиотеками, он просто описывает, как использовать существующие функции. Я думаю, этот вопрос заслуживает повторного открытия. –