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()
現在的問題似乎並沒有要求一個資源,而是一個實現,因爲所有其他問題也如此。 – Trilarion 2015-02-18 20:06:37
由於被關閉主題,我感到困惑。這並不是要求本身幫助尋找資源或工具,而是要求如何實施。無可否認,這有點寬泛,但接受的答案不涉及外部工具或庫,它僅僅描述如何使用現有的功能。我認爲這個問題值得重新打開。 – 2015-02-18 20:21:48