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

Python Tkinter 如何在状态栏中显示行号和列号

Tkinter 状态栏显示行号列号实现方法

你需要先添加文本编辑组件(Text),再绑定光标位置变化事件实时计算行列号更新到状态栏即可,完整实现代码如下:

from tkinter import *

def update_cursor_pos(event=None):
    # 获取当前光标位置
    cursor_pos = text_area.index(INSERT)
    # 分割得到行号和列偏移(列偏移默认从0开始,加1转为从1计数)
    line, col = cursor_pos.split('.')
    col = str(int(col) + 1)
    # 更新状态栏内容,也可单独用一个Label放右侧显示行列号
    StatusBarlabel.config(text=f'My Notepad | 行: {line} 列: {col}')

root = Tk()
root.title("Testing 6.py")
root.geometry('500x500')

# 文本编辑区域
text_area = Text(root, wrap=WORD)
text_area.pack(expand=True, fill=BOTH)
# 绑定光标位置变化触发更新的事件
text_area.bind('<KeyRelease>', update_cursor_pos)
text_area.bind('<ButtonRelease-1>', update_cursor_pos)

# 状态栏
StatusBar = Frame(root, width=10, borderwidth=1, relief=SUNKEN)
StatusBar.pack(side=BOTTOM, fill=X)
StatusBarlabel = Label(StatusBar, text='My Notepad')
StatusBarlabel.pack(side=LEFT)

# 初始化显示一次行列号
update_cursor_pos()

root.mainloop()

实现关键点说明

  • 核心通过Text组件的index(INSERT)方法获取当前插入光标的位置,返回值格式为行号.列偏移,其中行号默认从1开始计数,列偏移默认从0开始计数
  • 绑定KeyRelease(按键松开)、ButtonRelease-1(鼠标左键松开)两个事件,覆盖打字、点击移动光标两种常见的光标位置变更场景
  • 如果想让状态栏左侧显示软件名、右侧显示行列号,可以新增一个Label放在状态栏右侧,代码调整如下:
# 状态栏部分调整
StatusBarlabel = Label(StatusBar, text='My Notepad')
StatusBarlabel.pack(side=LEFT)
# 新增右侧行列号Label
cursor_pos_label = Label(StatusBar, text='行: 1 列: 1')
cursor_pos_label.pack(side=RIGHT)

# 对应更新函数里调整为修改cursor_pos_label的text
def update_cursor_pos(event=None):
    cursor_pos = text_area.index(INSERT)
    line, col = cursor_pos.split('.')
    col = str(int(col) + 1)
    cursor_pos_label.config(text=f'行: {line} 列: {col}')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 03:15:04