如何在tkinter中发生某些事件后删除标签

问题描述 投票:0回答:1

我有一个应用程序,只要发生某些事件,图像(使用Label(root,image ='my_image)创建的图像)都会更改。不使用按钮。我的一张图片上有一个标签,在图片上方有文字。所以它发生在我想要的地方。但是当我之后移动到下一张图像时,它仍然存在并且我不想要它。我能做什么?我试图销毁文本标签,但是它说变量在赋值之前被使用。这是我插入文本标签的部分。如果阻止,panel2变量将无法在外部运行,因此我无法销毁它:

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)
python tkinter label textlabel
1个回答
0
投票

您可以在画布上完成。在画布上放置标签,并对bindEnter事件使用Leave功能:

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

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

也如前所述,您可以将标签或其他objets存储在列表或字典中,以更改单独的对象,例如:

# 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()
© www.soinside.com 2019 - 2024. All rights reserved.