如何在Tkinter中更改按钮的可见性?

时间:2019-03-24 06:19:11

标签: python python-3.x tkinter

我是python的新手,正在尝试创建一个应用程序,在该应用程序中,我希望仅在单击“显示”按钮后才能看到按钮。该按钮从应用程序的开始就不可见,而应仅在单击“显示”按钮后才可见。你们可以帮我吗?

我有这段代码,该代码在单击另一个按钮后将其隐藏。隐藏按钮后,它将文本更改为“显示”。


from tkinter import *

root = Tk()

btn1 = Button(root,text="Example")
btn1.visible = True
btn1.place(x=20, y=50)
btn1.pi = btn1.place_info()

btn3 = Button(root, text="click me", command=lambda:plugin())
btn3.place(x=20, y=150)

def plugin():
    master = Tk()

    def toggle1():
        if btn1.visible:
            btnToggle1["text"] = "Show Example"
            print ("Now you don't")
            btn1.place_forget()
        else:
            btn1.place(btn1.pi)
            print ("Now you see it")
            btnToggle1["text"] = "Hide Example"
        btn1.visible = not btn1.visible


    btnToggle1 = Button(master, text="Hide Example", command=toggle1)
    btnToggle1.place(x=70, y=150)

    master.mainloop()

root.mainloop()

我希望仅在单击“显示”按钮后才显示该按钮,而不是一开始。

2 个答案:

答案 0 :(得分:0)

我希望这就是你的意思:

from tkinter import *
import tkinter

root = Tk()

btn1 = Button(root,text="Example")
btn1.visible = True
btn1.place(x=20, y=50)
btn1.pi = btn1.place_info()

btn3 = Button(root, text="click me", command=lambda:plugin())
btn3.place(x=20, y=150)

def plugin():
    master = Tk()

    def toggle1():
        if btn1.visible:
            btnToggle1["text"] = "Show Example"
            btnToggle1["state"] = DISABLED
            print ("Now you don't")
            btn1.place_forget()
        else:
            btn1.place(btn1.pi)
            print ("Now you see it")
            btnToggle1["state"] = NORMAL
            btnToggle1["text"] = "Hide Example"
        btn1.visible = not btn1.visible


    btnToggle1 = Button(master, text="Hide Example", command=toggle1)
    btnToggle1.place(x=70, y=150)

    master.mainloop()

root.mainloop()

答案 1 :(得分:0)

为了更改小部件的可见性,您必须使用 .pack_forget() 函数才能这样做。

此问题已在此处回答:In Tkinter is there any way to make a widget not visible?