字
字节笔记本
2026年5月1日
Go TUI 鼠标支持完全指南
API中转
¥120
这篇文章将介绍 Go 语言实现 TUI 鼠标交互的完整方案,包括点击、滚轮、拖拽等事件处理,推荐使用 Bubble Tea 框架快速实现。
Go TUI 鼠标支持概述
Go 做 TUI 时,鼠标点击、滚轮、拖拽一般不是 Go 语言本身提供,而是由 TUI 框架 / 终端协议支持。
常用方案对比
| 库 | 鼠标支持 | 适合场景 |
|---|---|---|
| Bubble Tea | ✅ 支持点击、滚轮、移动 | 现代 TUI,推荐 |
| tcell | ✅ 支持完整鼠标事件 | 底层终端控制 |
| termbox-go | ⚠️ 老库,支持有限 | 不太推荐新项目 |
| gocui | ✅ 支持鼠标 | 面板式 TUI |
| rivo/tview | ✅ 基于 tcell | 表格、表单、列表、布局 |
Bubble Tea 鼠标点击示例
最推荐的方案是使用 Bubble Tea 框架:
bash
go get github.com/charmbracelet/bubbletea完整示例代码
go
package main
import (
"fmt"
"os"
tea "github.com/charmbracelet/bubbletea"
)
type model struct {
msg string
}
func (m model) Init() tea.Cmd {
return nil
}
func (m model) Update(message tea.Msg) (tea.Model, tea.Cmd) {
switch msg := message.(type) {
case tea.MouseMsg:
switch msg.Type {
case tea.MouseLeft:
m.msg = fmt.Sprintf("左键点击:x=%d y=%d", msg.X, msg.Y)
case tea.MouseWheelUp:
m.msg = "鼠标滚轮向上"
case tea.MouseWheelDown:
m.msg = "鼠标滚轮向下"
}
case tea.KeyMsg:
if msg.String() == "q" || msg.String() == "ctrl+c" {
return m, tea.Quit
}
}
return m, nil
}
func (m model) View() string {
return fmt.Sprintf(`
Go TUI 鼠标点击测试
%s
用鼠标点一下终端窗口
按 q 退出
`, m.msg)
}
func main() {
p := tea.NewProgram(
model{msg: "等待鼠标点击..."},
tea.WithMouseCellMotion(),
)
if _, err := p.Run(); err != nil {
fmt.Println("启动失败:", err)
os.Exit(1)
}
}运行方式
bash
go run main.go鼠标事件启用方式
Bubble Tea 提供两种鼠标启用模式:
go
// 方式 1:单元格运动模式(推荐)
tea.WithMouseCellMotion()
// 方式 2:全运动模式(更强大)
tea.WithMouseAllMotion()技术原理
简单理解:
text
Go 本身不管鼠标
终端负责把鼠标事件转成 escape sequence
TUI 框架负责解析
你的 Go 程序收到 MouseMsg终端兼容性说明
- 不是所有终端都完整支持鼠标事件
- macOS Terminal、iTerm2、Windows Terminal 一般可以
- SSH 里也可以,但取决于远程终端和本地终端
推荐组合
如果你是新项目,直接用:
Bubble Tea + Lip Gloss
这是目前 Go 生态里写现代 TUI 最舒服的组合。
项目链接
- Bubble Tea:https://github.com/charmbracelet/bubbletea
- Lip Gloss:https://github.com/charmbracelet/lipgloss
分享: