Reputation: 93
I have a Text widget that contains two rows of text. I need to get the row when i click on it. For example if i click on the second row of text ı should get the only second row of text. I tried to bind it but it didnt work.
And also there is an another problem. Bind function only works for one time. If i click on the Text widget second time it does not work. My code is getting every row of text not that i clicked on.
from tkinter import *
import time
root = Tk()
clicked = StringVar()
text = Text(root,height = 10, width = 30,relief = SUNKEN )
text.grid(row = 0, column = 0,padx = 20,pady = 20)
text.insert(END,"Oda the Elder\nJohn the Baptist")
def getelement(event):
for t in range(1,3):
get_ = text.get(f"{t}.0",f"{t+1}.0")
print(get_)
text.bind("<FocusIn>",getelement)
but = Button(root,text = "click")
but.grid(row = 1, column = 0)
root.mainloop()
Upvotes: 1
Views: 73
Reputation: 385980
You can bind to the button click event (<1>
). Within the function you can get the index based on the x/y of the mouse at the time of the click. From that you can get the text of that whole line by modifying the index with "linestart" and "lineend".
The function would look something like this:
def getelement(event):
index = event.widget.index(f"@{event.x},{event.y}")
text = event.widget.get(f"{index} linestart", f"{index} lineend")
print(text)
The binding would look like this:
text.bind("<1>",getelement)
Upvotes: 1
Reputation: 958
You can't do this with the Text box as everything is inside that text box only. The lines are theoretically defined. You want to use a Listbox
Syntax
Here is the simple syntax to create this widget −
w = Listbox ( master, option, ... )
Parameters
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
Below is an example of code:
from tkinter import *
top = Tk()
Lb1 = Listbox(top)
Lb1.insert(1, "Python")
Lb1.insert(2, "Perl")
Lb1.insert(3, "C")
Lb1.insert(4, "PHP")
Lb1.insert(5, "JSP")
Lb1.insert(6, "Ruby")
def items_selected(event):
""" handle item selected event
"""
# get selected indices
selected_indices = Lb1.curselection()
# get selected items
selected_langs = ",".join([Lb1.get(i) for i in selected_indices])
msg = f'You selected: {selected_langs}'
print(msg)
Lb1.bind('<<ListboxSelect>>', items_selected)
Lb1.pack()
top.mainloop()
Upvotes: 0