python如何读取字符串最后一个字符_获取文本窗口中最后一个字符的位置

此篇博客介绍了如何使用Python的Tkinter库获取文本小部件中字符右下角的屏幕坐标,通过计算字符边界框尺寸并加上小部件位置来实现。适合理解文本处理和GUI编程的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文本光标处字符右下角的屏幕坐标可以通过以下方法确定:取该字符的边界框,并将宽度和高度添加到坐标中,以获得与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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值