我正在使用什么:Tkinter
我想要的是:創建一個帶有關鍵字的文本,當游標懸停在它們上方時將突出顯示,并在單擊它時執行系結到它們的功能。將來我計劃將附加資訊系結到這些單詞
現在它看起來如何:我發現最接近的事情是如何在懸停并單擊Label使用bind()函式(如bind("<Enter>", red_text))中的文本時呼叫函式。但是這樣我就沒有辦法改變一個特定的詞了。另外,如果事實證明做我想做的唯一方法是Labels為每個句子和關鍵字創建個體,然后也將它們設定,那么我不知道如何使它更簡單
對于我需要它和我期望看到的:我希望能夠撰寫小說文本,稍后將在其中確定關鍵字。這些關鍵字在激活后將為它們提供預先創建的答案選項
一個更具說明性的例子:
文本:Hello, world!,其中主要文本顯示為非粗體和斜體,關鍵字相反 -粗體和非斜體。字體為白色
關鍵字:“ world ” - 與改變和回傳原始顏色的函式系結(取決于游標是否指向它)和一個更復雜的函式,當點擊時,它在單獨的視窗中提供答案選擇(最初包含標準答案)
在按下關鍵字之前回答選項:
1. Hi!
之后:
1. What world?
2. The world is me?
3. Who are you talking to?
uj5u.com熱心網友回復:
您可以在滑鼠移動時創建系結<Motion>以呼叫函式。在回呼中,您可以使用類似的索引找到游標下字符的索引"@x,y",并從中獲取單詞。
然后,您可以在該單詞上添加一個標簽,設定一些標記以幫助您在回呼中找到該單詞,并在標簽上系結一個在單擊小部件時呼叫函式的標簽。
這是一個例子:
import tkinter as tk
root = tk.Tk()
text = tk.Text(root, width=80, height=10)
label = tk.Label(root, text="")
label.pack(side="bottom", fill="y")
text.pack(fill="both", expand=True)
text.tag_configure("keyword", background="black", foreground="white")
text.insert("end", "Hello, world!\nThis has another hidden keyword\n")
keywords = ["world", "another"]
def hover(event):
text = event.widget
keyword_start = text.index(f"@{event.x},{event.y} wordstart")
keyword_end = text.index(f"@{event.x},{event.y} wordend")
word = text.get(keyword_start, keyword_end)
text.tag_remove("keyword", "1.0", "end")
if word in keywords:
text.mark_set("keyword_start", keyword_start)
text.mark_set("keyword_end", keyword_end)
text.tag_add("keyword", keyword_start, keyword_end)
def keyword_click(event):
text = event.widget
word = text.get("keyword_start", "keyword_end")
label.configure(text=f"you clicked on the word '{word}'")
text.bind("<Motion>", hover)
text.tag_bind("keyword", "<1>", keyword_click)
root.mainloop()

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/483747.html
