簡體   English   中英

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

[英]Get position of last character in Tkinter Text widget

我不想要rowcolumn ,而是想要屏幕上的實際坐標。 我需要此信息,因為我想在用戶鍵入的位置下方放置一個listbox

可以通過以下操作來確定文本光標處字符右下角的屏幕坐標:確定該字符的邊界框,然后將坐標的寬度和高度相加,以獲得相對於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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM