【问题标题】:How to delete label after some event in tkinter如何在 tkinter 中的某些事件后删除标签
【发布时间】:2020-07-19 17:59:07
【问题描述】:

我有一个应用程序,其中的图像(使用 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)

【问题讨论】:

  • 将标签存储在数组中
  • 为什么不在程序启动时创建该标签,然后根据common.dynamic_data 的值更新其文本?

标签: python tkinter label textlabel


【解决方案1】:

你可以在画布上做。在画布上放置标签并为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')

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

【讨论】:

  • 图片改变后会破坏标签吗?
猜你喜欢
  • 2021-05-28
  • 1970-01-01
  • 2011-06-20
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 2018-05-31
相关资源
最近更新 更多