如何在tkinter中的某个事件后删除标签

2024-06-16 12:28:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个应用程序,每当发生某个事件时,图像(使用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)

Tags: to图像image文本应用程序dataifdynamic
1条回答
网友
1楼 · 发布于 2024-06-16 12:28:42

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

# 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')

或者只需在上一行中添加两行即可将它们组合起来

相关问题 更多 >