我正在嘗試使用 Tkinter 和 Python 3.10 制作一個簡單的 HTML 編輯器。現在我正在嘗試使用 Tkinter Text 小部件實作自動完成。小部件檢查當前鍵入的單詞,看它是否與 .html 中的任何 HTML 標記匹配self._tags_list。如果是這樣,它會自動完成它。
代碼:
import random
import tkinter as tk
class IDE(tk.Text):
def __init__(self, *args, **kwargs):
tk.Text.__init__(self, *args, **kwargs)
self._tags_list = ['<html></html>', '<head></head>', '<title></title>', '<body></body>', '<h1></h1>',
'<h2></h2>', '<h3></h3>', '<h4></h4>', '<h5></h5>', '<h6></h6>', '<p></p>', '<b></b>']
self.bind("<Any-KeyRelease>", self._autocomplete)
self.bind("<Tab>", self._completion, add=True)
self.bind("<Return>", self._completion, add=True)
def callback(self, word):
# Returns possible matches of `word`
matches = [x for x in self._tags_list if x.startswith(word)]
return matches
def _completion(self, _event):
tag_ranges = self.tag_ranges("autocomplete")
if tag_ranges:
self.mark_set("insert", tag_ranges[1])
self.tag_remove("sel", "1.0", "end")
self.tag_remove("autocomplete", "1.0", "end")
return "break"
def _autocomplete(self, event):
if event.keysym not in ["Return"] and not self.tag_ranges("sel"):
self.tag_remove("sel", "1.0", "end")
self.tag_remove("autocomplete", "1.0", "end")
word = self.get("insert-1c wordstart", "insert-1c wordend")
print(f"word: {word}")
matches = self.callback(word)
print(f"matches: {matches}")
if matches:
remainder = random.choice(matches)[len(word):]
print(remainder)
insert = self.index("insert")
self.insert(insert, remainder, ("sel", "autocomplete"))
self.mark_set("insert", insert)
return
if __name__ == "__main__":
window = tk.Tk()
window.title("Autocomplete")
window.geometry("500x500")
text = IDE(window)
text.pack(fill=tk.BOTH, expand=True)
從
有人可以告訴我為什么會發生這種情況以及如何解決嗎?我查遍了周圍,還沒有發現任何東西。對不起,如果很明顯,但我現在正在學習 Tkinter。另外,如果代碼中還有其他問題,請告訴我。
uj5u.com熱心網友回復:
一個詞wordstart定義為
“一個詞要么是一串連續的字母、數字或下劃線 (_) 字符,要么是不是這些型別的單個字符。”
當您在 之后鍵入更多字符時<,wordstart從 . 旁邊的字符開始<。您可以通過-1c在 wordstart 末尾添加來完成這項作業
word = self.get("insert -1c wordstart -1c", "insert -1c wordend")
通過添加
if "<" in word:
word = word[word.index("<"):]
word稍有改善后即可。
除此之外,您還需要從鍵盤符號中排除 BackSpace、Ctrl a 等
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/482708.html
下一篇:通用查詢解決方案
