单击 tkinter 按钮显示/隐藏标签

时间:2021-03-02 17:47:55

标签: python-3.x tkinter button label show-hide

我想通过单击按钮隐藏标签并通过单击相同的按钮显示相同的标签,我想在单击的按钮下方显示这些标签。我已经尝试了下面的代码,但是通过单击任何按钮,只有 collaborate 标签在下面的 button2 中可见。但我希望它就像我点击button1一样,“开始”标签应该出现在button1的下方,如果我点击button2,“ >collaborate" 标签应该出现在 button2 的下方

import tkinter as tk

root=tk.Tk()

def label_hide_show():
    global hidden
    if hidden:
        label1.pack(side = "top", fill = tk.BOTH)
        hidden = False
    else:
        label1.pack_forget()
        hidden=True
            
hidden = True

btn1 = tk.Button(root, text="Get Started", height=3,width=26,bg="White", fg="Black", command=label_hide_show)
label1 = tk.Label(root, text="Get started")
        
btn1.pack(side = "top", fill = tk.BOTH)

btn2 = tk.Button(root, text="Collaborate", height=3,width=26,bg="White", fg="Black", command=label_hide_show)
label1 = tk.Label(root, text="Collaborate")
        
btn2.pack(side = "top", fill = tk.BOTH)

以上代码的输出:

enter image description here

1 个答案:

答案 0 :(得分:1)

想到的第一个似乎很简单的解决方案是使用单个标签,并根据单击的按钮更新其文本。因此,您应该将函数更改为:

def label_hide_show(btn):
    global hidden
    if hidden:
        label1.config(text=btn.cget('text')) # Change text to clicked buttons text
        label1.pack(side = "top", fill = tk.BOTH)
        hidden = False
    else:
        label1.pack_forget()
        hidden=True

btn1 = tk.Button(root, text="Get Started", height=3,width=26,bg="White", fg="Black", command=lambda: label_hide_show(btn1))

label1 = tk.Label(root) # Make sure to just use one of this label

btn2 = tk.Button(root, text="Collaborate", height=3,width=26,bg="White", fg="Black", command=lambda: label_hide_show(btn2))

这样你就可以让它随着被点击的按钮的文本而更新。

显然,还有其他方法,例如传递您想要显示的文本而不是将按钮作为参数传递:

def label_hide_show(text):
    global hidden
    if hidden:
        label1.config(text=text)
        label1.pack(side = "top", fill = tk.BOTH)
        hidden = False
    else:
        label1.pack_forget()
        hidden=True

btn1 = tk.Button(root, text="Get Started", height=3,width=26,bg="White", fg="Black", command=lambda: label_hide_show('Get started'))

此方法的用途是,您可以使用/传递按钮文本以外的任何文本。此方法的其他变体包括使用 StringVar() 并在其上调用 set() 以更改标签文本,本质上是相同的原理,但使用的方式不同。

更新: 好像我看错了你的问题,还是很简单,下面是一个例子:

def label_hide_show(btn,text):
    global hidden
    if hidden:
        label1.config(text=text) # Change to passed text
        label1.pack(side = "top", fill = tk.BOTH, after=btn) # Pack it after the btn
        hidden = False
    else:
        label1.pack_forget()
        hidden=True

btn1 = tk.Button(root, text="Get Started", height=3,width=26,bg="White", fg="Black", command=lambda: label_hide_show(btn1,'Label below one'))
btn2 = tk.Button(root, text="Collaborate", height=3,width=26,bg="White", fg="Black", command=lambda: label_hide_show(btn2,'Label below two'))

现在标签将放置after传递的按钮。