我目前有一个日志解析器,可以将用户信息放入文本小部件中。如果插入文本小部件的行有关键字,则该行将以蓝色突出显示。如果单击该行,我想在执行的事件函数中使用该行的文本。
因为我正在使用我的标签的配置将线条着色为蓝色,所以我不能也复制点击的文本吗?
代码示例:
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()
如何获取被点击的用户名并在函数中使用它?我只想将用户名设置为一个变量并使用它,我只是不知道如何去做。
最佳答案
你可以为每个点击的文本使用单独的标签,然后你可以将它作为参数发送给绑定(bind)函数
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()
关于python - Tkinter 文本小部件 - 在事件函数中使用单击的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40940397/