You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Tkinter Text组件右键点击事件的行.列索引?

在tk.Text中获取右键点击位置的行.列索引

要实现你需要的功能,tk.Text本身没有直接的get_right_click_index方法,但可以通过绑定右键事件+利用Text组件的index方法来实现,具体步骤如下:

  • 给Text组件绑定右键点击事件(Windows/Linux用<Button-3>,Mac用<Button-2>,可同时绑定做兼容)
  • 在事件处理函数中,通过event.widget.index(f"@{event.x},{event.y}")获取点击位置对应的行.列索引

完整示例代码

import tkinter as tk

def get_right_click_index(event):
    # 获取右键点击位置的行.列索引
    rc_index = event.widget.index(f"@{event.x},{event.y}")
    print(rc_index)
    return rc_index

root = tk.Tk()
text = tk.Text(root)
text.insert("1.0", "this is a test text.\nwhich has two lines.")
text.pack()

# 绑定右键事件,兼容不同平台
text.bind("<Button-3>", get_right_click_index)
text.bind("<Button-2>", get_right_click_index)  # Mac平台右键

root.mainloop()

说明

  • index("@x,y")是tk.Text的内置语法,会将鼠标点击的坐标(相对于Text组件的内部坐标)转换为行.列格式的索引,完全符合你的需求
  • 当你右键点击第二行"which"的第一个"h"起始位置时,会输出2.1,和预期一致

内容的提问来源于stack exchange,提问作者rocketsfallonrocketfalls

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 01:55:25