I’m a newbie in Python and for practice, I’m trying to make a listbox follow my text cursor in a Text widget using tkinter. (The moving listbox will basically serve as a autocomplete tool.) Here’s the closest question to mine: Is it possible to convert tkinter text index to coordinates? but unfortunately there’s a better workaround for the thread poster’s problem, so the main question wasn’t answered.
I also tried to use Text.window_create(), which uses index to position windows, but the window/widget is treated like a text and gets deleted if I press backspace/delete. Tried looking into its internal code but I can’t understand :D
Here’s my code:
def textChanged(event):
index = text1.index(tk.INSERT)
# coord = from index ??
# list1.place(coord[0],coord[1]
if __name__==‘__main__’:
root = Tk()
text1 = Text(root)
text1.place(x=0,y=0)
text1.bind(“<KeyRelease>“,textChanged)
list1 = Listbox(root)
Thanks!
CodePudding user response:
You can use text1.bbox(tk.INSERT)[:2]
to get the coordinates (relative to text1
) of the insertion cursor. However since list1
is a child of root
window, it is better to offset this coordinates by the position of text1
inside root
window:
def textChanged(event):
# get the coordinates of text box inside root window
x0, y0 = text1.winfo_x(), text1.winfo_y()
# get the coordinates of the insertion cursor inside text box
x1, y1 = text1.bbox(INSERT)[:2]
# the coordinates of the insertion cursor relative to root window
# will be (x0 x1, y0 y1)
list1.place(x=x0 x1, y=y0 y1)