2016-12-02 48 views
1

我目前有一個日誌解析器,可將用戶信息放入文本小部件中。如果插入到「文本」窗口小部件中的某行具有關鍵字,則該行將突出顯示爲藍色。如果該線被點擊,我想在執行的事件函數中使用該行中的文本。Tkinter文本小部件 - 在事件功能中使用單擊的文本

因爲我正在使用我的標記的配置顏色藍線,我不能還複製點擊文本?代碼

例子:

from tkinter import * 


def callback(event): 
    window = Toplevel() 
    window.overrideredirect(1) 
    window.geometry("200x100+{0}+{1}".format(event.x_root-1, event.y_root-12)) 
    label = Label(window, justify="left", text="Username: value \nLocation: value \nAddress: value \nSecurity Level: value") 
    label.grid() 
    window.bind("<Leave>", lambda e: window.destroy()) 

root = Tk() 
text = Text(root) 
text.insert(END, "Click here", "tag") 
text.pack() 
text.tag_config("tag", foreground="blue") 
text.tag_bind("tag", "<Button-1>", callback) 

root.mainloop() 

我如何可以採取被點擊,並在函數中使用它的用戶名?我只想將用戶名設置爲一個變量並使用它,我只是想念如何去做。

回答

2

您可以使用單獨的標籤爲每個點擊的文本,然後你可以把它作爲參數傳遞給綁定功能

import tkinter as tk 


def callback(event, tag): 
    print(event.widget.get('%s.first'%tag, '%s.last'%tag)) 

root = tk.Tk() 

text = tk.Text(root) 
text.pack() 

text.tag_config("tag1", foreground="blue") 
text.tag_bind("tag1", "<Button-1>", lambda e:callback(e, "tag1")) 
text.insert(END, "first link", "tag1") 

text.insert(END, " other text ") 

text.tag_config("tag2", foreground="blue") 
text.tag_bind("tag2", "<Button-1>", lambda e:callback(e, "tag2")) 
text.insert(END, "second link", "tag2") 

root.mainloop() 

編輯:

我發現如何轉換鼠標位置並找到點擊標籤,因此它不需要單獨的標籤。

Python TKinter get clicked tag in text widget

import tkinter as tk 


def callback(event): 
    # get the index of the mouse click 
    index = event.widget.index("@%s,%s" % (event.x, event.y)) 

    # get the indices of all "adj" tags 
    tag_indices = list(event.widget.tag_ranges('tag')) 

    # iterate them pairwise (start and end index) 
    for start, end in zip(tag_indices[0::2], tag_indices[1::2]): 
     # check if the tag matches the mouse click index 
     if event.widget.compare(start, '<=', index) and event.widget.compare(index, '<', end): 
      # return string between tag start and end 
      print(start, end, event.widget.get(start, end)) 

root = tk.Tk() 

text = tk.Text(root) 
text.pack() 

text.tag_config("tag", foreground="blue") 
text.tag_bind("tag", "<Button-1>", callback) 

text.insert(END, "first link", "tag") 

text.insert(END, " other text ") 

text.insert(END, "second link", "tag") 

root.mainloop() 
+0

我不得不準備回調3次或4次以瞭解它在做什麼。這處理我需要的一切。感謝您的幫助。 – sidnical

2

您不應該創建Tk的第二個實例。如果您需要一個彈出窗口,請創建一個Toplevel的實例。您也不需要再撥打mainloop

您可以使用您單擊的x,y座標獲取單擊的索引。例如:text.index("@%d,%d" % (event.x, event.y))

+0

我是從我的東西在其他線程複製拋例如在一起,我沒有看到第二個主循環或傳統知識的秒實例。通常不會那樣做,但感謝他們指出。我會修復這個例子。 – sidnical

+0

獲取索引會給我單詞的位置,但是如何選擇單詞以將其設置爲變量? – sidnical

+0

@sidnical:將標籤'sel'添加到您想要選擇的任何區域。 –

相關問題