在 tkinter 中创建鼠标悬停在文本框上 [英] Creating a mouse over text box in tkinter

查看:26
本文介绍了在 tkinter 中创建鼠标悬停在文本框上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个系统,当用户指向一个对象时,会出现一个文本框,其中包含我尚未实现的某些信息,然后在他们将鼠标移开时消失.我试图通过绑定 < 来做到这一点.输入 > 和 <离开 > 命令,但是当我运行以下代码时没有任何反应,除了在终端中它说 destroy 需要两个参数,所以我知道它正在调用函数.

I'm trying to implement system where when the user points to an object, a text box appears with certain information which I haven't implemented yet, then disappears when they move their mouse away. I'm trying to do that by binding the < Enter > and < Leave > commands, but nothing happens when I run the following code, except that in the terminal it says that destroy requires two arguments, so I know it is calling the functions.

from tkinter import *

xhig, yhig = 425,325
bkgnclr = '#070707'
currentmouseoverevent = ''

c = Canvas(master, width=xhig*2, height=yhig*2, bg=bkgnclr, cursor = 'crosshair',)

def mouseovertext(event):
    mouseover = "Jack"
    currentmouseoverevent = event
    c.create_rectangle(bbox=(event.x,event.y, (event.x + 5), (event.y +len(mouseover)*5)),outline="white", fill=bkgnclr, width= len(mouseover))
    c.create_text(position=(event.x,event.y),text=mouseover, fill="white", currentmouseoverevent=event)

def closemouseover(x):
    c.destroy(currentmouseoverevent)

c.bind("<Enter>", mouseovertext)
c.bind("<Leave>", closemouseover)

destroy 需要什么参数,为什么不创建矩形?

What arguments does destroy take, and why is the rectangle not being created?

推荐答案

更正后的代码如下.

事实证明我调用 bbox 是错误的.不是将坐标作为元组传递,我应该将它们作为 create_rectangle 的前四个 agrguments 传递.c.destroy 仅用于画布、条目或文本框等对象,而我使用 c.delete 删除项目,并使用 c.create_rectangle 和 c.create_text 返回的事件编号.

It turns out I was calling bbox wrong. Instead of passing the coords as a tuple, I should have passed them as the first four agrguments of create_rectangle. c.destroy is only for objects like canvas, entry or textbox, instead I used c.delete for deleting items, and used the event number returned by c.create_rectangle and c.create_text.

from tkinter import *

xhig, yhig = 425,325
bkgnclr = '#070707'
currentmouseoverevent = ['','']

c = Canvas(master, width=xhig*2, height=yhig*2, bg=bkgnclr, cursor = 'crosshair',)

def mouseovertext(event):
    mouseover = "Jack"

    if currentmouseoverevent[0] != '':
    closemouseover()
    currentmouseoverevent[0]=''
    return
currentmouseoverevent[0] = c.create_rectangle(event.x,event.y, (event.x + 5), (event.y +len(mouseover)*5),outline="white", fill=bkgnclr, width= len(mouseover))
 currentmouseoverevent[1] = c.create_text(event.x,event.y,text=mouseover, fill="white", currentmouseoverevent=event,anchor=NW)

def closemouseover(x):
    c.delete(currentmouseoverevent[0])
    c.delete(currentmouseoverevent[1])

c.bind("<Button-3", mouseovertext)

这篇关于在 tkinter 中创建鼠标悬停在文本框上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆