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

PySimpleGUI表格行鼠标悬停高亮实现方法问询

在PySimpleGUI中实现表格行鼠标悬停高亮效果

要实现PySimpleGUI表格的行悬停高亮,核心是监听鼠标移动事件并动态切换高亮行。你的原代码仅监听了表格点击事件,所以无法触发悬停效果,以下是修改后的完整解决方案:

import PySimpleGUI as sg

data = [
    ['John', 25, 'Engineer'],
    ['Alice', 30, 'Designer'],
    ['Bob', 28, 'Developer'],
]

# 定义表格布局
layout = [
    [
        sg.Table(
            values=data,
            headings=['Name', 'Age', 'Occupation'],
            display_row_numbers=True,
            auto_size_columns=False,
            justification='left',
            key='-TABLE-'
        )
    ]
]

window = sg.Window('Hover Highlight Example', layout, finalize=True)
table = window['-TABLE-']
# 绑定鼠标移动和离开事件
table.bind('<Motion>', '_MOTION')
table.bind('<Leave>', '_LEAVE')

last_hovered_row = None  # 记录上一次悬停的行,避免重复高亮

while True:
    event, values = window.read()
    if event in (sg.WIN_CLOSED, 'Exit'):
        break
    # 处理鼠标移动事件
    if event == '-TABLE-_MOTION':
        # 获取鼠标所在的行号(tkinter原生方法,表头对应行0,数据行从1开始)
        row_idx = table.Widget.identify_row(event.y)
        if row_idx:
            row = int(row_idx) - 1  # 转换为表格数据的索引(从0开始)
            # 只在新行和上次悬停行不同时更新
            if row != last_hovered_row and 0 <= row < len(data):
                table.highlight(row)
                last_hovered_row = row
    # 处理鼠标离开表格事件,清除高亮
    elif event == '-TABLE-_LEAVE':
        if last_hovered_row is not None:
            table.highlight(-1)  # 传入-1清除所有高亮
            last_hovered_row = None

window.close()

关键说明:

  • 窗口初始化必须加finalize=True,确保窗口显示前就能绑定事件
  • 通过bind方法给表格绑定<Motion>(鼠标移动)和<Leave>(鼠标离开)事件
  • 用tkinter原生的identify_row方法获取鼠标所在行,表头对应行0,所以要减1得到数据行的索引
  • 记录last_hovered_row避免重复触发高亮,提升性能
  • 鼠标离开表格时,调用highlight(-1)清除所有高亮

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 07:52:18