Henry Zhu
Henry Zhu

Reputation: 2628

Get position of last character in Tkinter Text widget

I don't want the row and column, but rather I want the actual coordinates on the screen. I need this information because I want to place a listbox right below where the user is typing.

Upvotes: 1

Views: 1324

Answers (1)

BlackJack
BlackJack

Reputation: 4689

The screen coordinates of the lower right corner of the character at the text cursor can be determined by taking the bounding box of that character and adding width and height to the coordinates to get the coordinates relative to the Text widget and then adding the screen coordinates of the top left corner of that widget:

#!/usr/bin/env python
from __future__ import absolute_import, division, print_function
import Tkinter as tk


class MainFrame(tk.Frame):

    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.text = tk.Text(self)
        self.text.pack(side=tk.TOP)
        tk.Button(
            self, text='print coordinate', command=self.print_coordinate
        ).pack(side=tk.TOP)

    def print_coordinate(self):
        """Calculate and print the lower right screen coordinate of the
        character at the current text cursor position.
        """
        character = self.text.get(tk.INSERT) 
        x, y, width, height = self.text.bbox(tk.INSERT)
        # 
        # The line end has a width spanning the whole line until the right
        # border of the text widget but it makes more sense to view it as
        # having zero width in this context.
        # 
        screen_x = x + (0 if character == u'\n' else width) + self.winfo_rootx()
        screen_y = y + height + self.winfo_rooty()
        print(screen_x, screen_y)


def main():
    root = tk.Tk()
    mainframe = MainFrame(root)
    mainframe.pack()
    root.mainloop()


if __name__ == '__main__':
    main()

Upvotes: 6

Related Questions