在Tkinter Text小部件中获取最后一个字符的位置

Hen*_*Zhu 1 python tkinter

我不需要rowand column,但是我想要屏幕上的实际坐标。我需要此信息,因为我想listbox在用户键入的位置下方放置一个右侧。

Bla*_*ack 5

可以通过以下方式确定文本光标处字符右下角的屏幕坐标:确定该字符的边界框,然后将坐标的宽度和高度相加,以获得相对于Text小部件的坐标,然后将其的屏幕坐标相加该小部件的左上角:

#!/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()
Run Code Online (Sandbox Code Playgroud)