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

如何为tkinter画布中的矩形对象添加Pmw tooltip提示框

问题解决方案

报错原因

  • Pmw.Balloon初始化时仅接受Tkinter原生控件作为父容器,你传入了自定义的Bar类实例,该实例没有Tkinter控件要求的tk属性,直接触发属性错误
  • Canvas上绘制的矩形属于Canvas内部管理的图元,不是独立的Tkinter控件,无法直接调用Pmw的绑定方法

修复后可运行代码

from tkinter import *
import Pmw

root = Tk()
Pmw.initialise(root)
canvas = Canvas(width=800, height=700, bg='white')

class Bar:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        # 保存矩形的图元ID
        self.bar_id = canvas.create_rectangle(x, y, x + 200, y + 200, fill='pink')

bar = Bar(200, 200)
# Balloon绑定到Canvas原生控件
balloon = Pmw.Balloon(canvas)
# 自定义悬停检测逻辑
def on_mouse_move(event):
    # 查询当前鼠标坐标下的所有Canvas图元
    hover_items = canvas.find_overlapping(event.x, event.y, event.x, event.y)
    if bar.bar_id in hover_items:
        balloon.showtip("Text for the tool tip")
    else:
        balloon.hidetip()

# 绑定Canvas的鼠标移动事件
canvas.bind("<Motion>", on_mouse_move)
# 自定义Tooltip样式
lbl = balloon.component("label")
lbl.config(background="black", foreground="white")

canvas.pack()
root.mainloop()

核心实现逻辑

  • 调整Balloon的父容器为Canvas原生控件,符合Pmw的参数要求
  • 通过Canvas的find_overlapping方法实时检测鼠标位置下的图元,匹配到目标矩形时触发Tooltip显示,离开时隐藏
  • 该方案也可以扩展到绑定多个Canvas图元,只需要维护图元ID和对应Tooltip文本的映射关系即可

内容的提问来源于stack exchange,提问作者mr. bug

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 12:45:02