我正在尝试实现系统,当用户指向某个对象时,会出现一个文本框,其中包含我尚未实现的某些信息,然后当他们将鼠标移开时消失。我试图通过绑定<输入>和<离开>命令,但是当我运行以下代码时没有任何反应,除了在终端中它说destroy需要两个参数,所以我知道它正在调用函数。
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)
破坏采取什么参数,为什么没有创建矩形?
答案 0 :(得分:1)
tkinter中的边界框(bbox)是一个4元组,它存储矩形的边界。您只是在鼠标位置传递,这是一个2元组。
此外,在您显示的代码中使用它之前,您实际上从未实际分配变量“currentmouseoverevent”,因此您的closemouseover函数将失败。
答案 1 :(得分:0)
更正后的代码如下。
事实证明我在调用bbox是错误的。我应该将它们作为create_rectangle的前四个参数传递给而不是将coords作为元组传递。 c.destroy仅适用于canvas,entry或textbox等对象,而是使用c.delete删除项目,并使用c.create_rectangle和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)