0
我不想要row
和column
,而是我想要屏幕上的實際座標。我需要這些信息,因爲我想在用戶輸入的地方下方放置一個listbox
。獲取Tkinter Text小部件中最後一個字符的位置
我不想要row
和column
,而是我想要屏幕上的實際座標。我需要這些信息,因爲我想在用戶輸入的地方下方放置一個listbox
。獲取Tkinter Text小部件中最後一個字符的位置
在文本光標處字符右下角的屏幕座標可以通過獲取該字符的邊界框並將寬度和高度添加到座標來確定相對於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()
你怎麼知道用戶在最後一個字符?獲取插入字符的座標不是更好嗎? –