首页 > 解决方案 > 如何在 tkinter 中的某些事件后删除标签

问题描述

我有一个应用程序,其中的图像(使用 Label(root,image='my_image) 创建)会在发生某些事件时发生变化。不使用按钮。我的一张图片有一个标签,上面有图片上面的文字。所以它发生在我想要的地方。但是当我在那之后移动到下一张图片时,它仍然在那里,我不想要它。我能做些什么?我试图破坏()文本标签,但它说该变量是在分配之前使用的。这是我插入文本标签的部分。panel2 变量在 if 块之外不起作用,因此我无法销毁它:

if common.dynamic_data:
        to_be_displayed = common.dynamic_data
        panel2 = tk.Label(root, text = to_be_displayed, font=("Arial 70 bold"), fg="white", bg="#9A70D4")
        panel2.place(x=520,y=220)

标签: pythontkinterlabeltextlabel

解决方案


你可以在画布上做。在画布上放置标签并使用bind函数EnterLeave事件:

# imports
import tkinter as tk

# creating master
master = tk.Tk()

# hover functions
def motion_enter(event):
    my_label.configure(fg='green')
    print('mouse entered the canvas')

def motion_leave(event):
    my_label.configure(fg='grey')
    print('mouse left the canvas')

# create canvas, on which if you hover something happens
canvas = tk.Canvas(master, width=100, height=100, background='grey')
canvas.pack(expand=1, fill=tk.BOTH)

# create label
my_label = tk.Label(canvas, text='Toggle text is here!', fg='grey')
my_label.pack()

# binding enter and leave functions
master.bind('<Enter>', motion_enter)
master.bind('<Leave>', motion_leave)

# set window size
master.geometry('400x200')

# start main loop
master.mainloop()

当您悬停画布或创建函数中的任何其他内容时,您可以更改任何对象的配置。玩弄对象和代码来做任何你想做的事。

同样正如提到的,您可以将标签或其他对象存储在列表或字典中以更改单独的对象,例如:

# imports
import tkinter as tk

# creating master
master = tk.Tk()

d = {}

# hover functions
def motion_enter(event):
    d['first'].configure(fg='green')
    print('mouse entered the canvas')

def motion_leave(event):
    d['first'].configure(fg='grey')
    print('mouse left the canvas')

# create canvas, on which if you hover something happens
canvas = tk.Canvas(master, width=100, height=100, background='grey')
canvas.pack(expand=1, fill=tk.BOTH)

# create label
my_label = tk.Label(canvas, text='Toggle text is here!', fg='grey')
my_label.pack()
d['first'] = my_label
my_label = tk.Label(canvas, text='Toggle text is here!', fg='grey')
my_label.pack()
d['second'] = my_label

# binding enter and leave functions
master.bind('<Enter>', motion_enter)
master.bind('<Leave>', motion_leave)

# set window size
master.geometry('400x200')

# start main loop
master.mainloop()

编辑 1

如果要在鼠标离开画布时删除标签,可以编写这样的函数:

def motion_enter(event):
    d['first'].pack()
    d['second'].pack()
    print('mouse entered the canvas')

def motion_leave(event):
    d['first'].pack_forget()
    d['second'].pack_forget()
    print('mouse left the canvas')

或者只是在前面添加 2 行来组合它们。


推荐阅读