[英]How can I keep track of which text entry is clicked?
If I have a Tkinter Text widget with the text bound to a mouse click, how can I keep track of which text the user clicks on?如果我有一个文本绑定到鼠标单击的 Tkinter 文本小部件,我如何跟踪用户单击的文本? I want the function to return the number of the label clicked, but as it stands it only prints the last value of n which is 5. For example, if the user clicks "Name 1", I want it to print "1", if the user clicks on "Name 2", I want it to return "2".我希望该函数返回单击的标签编号,但就目前而言,它只打印 n 的最后一个值,即 5。例如,如果用户单击“名称 1”,我希望它打印“1”,如果用户单击“名称 2”,我希望它返回“2”。
Here is the code:这是代码:
import tkinter as tk
def prt(num):
print(num)
root = tk.Tk()
t = tk.Text(root, height=20, width=50)
t.pack()
for n in range(1, 6):
t.insert(tk.END, "%s %d\n" % ("Name", n), "label")
t.tag_bind("label", "<Button-1>", lambda event, num = n: prt(num))
root.mainloop()
Any help appreciated.任何帮助表示赞赏。
Thanks to jasonharper for providing the answer.感谢 jasonharper 提供答案。 Here is the working code.这是工作代码。
import tkinter as tk
def prt(num):
print(num)
root = tk.Tk()
t = tk.Text(root, height=20, width=50)
t.pack()
for n in range(1, 6):
t.insert(tk.END, "%s %d\n" % ("Name", n), "label%d" % n)
t.tag_bind("label%d" % n, "<Button-1>", lambda event, num = n: prt(num))
root.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.