Skip to content
Advertisement

Buttons in tkinter – When clicked: reveal something behind it

I am new to python and tkinter. I’m looking to make a simple window with a few buttons. When a button is pressed, I wish for it to disappear and instead reveal something behind it, a number, for instance.

How do I go about doing this? Below is an example code which generates a window with a button. Can I work with a code like this or should it look completely different?

from tkinter import *


class Button:
    def __init__(self):

        self.root = Tk()

        self.root.title("Button program")
        self.root.geometry("100x100")

        self.frame = Frame(self.root)

        self.btn = Button(self.root, width=2)
        self.btn.grid(row=1, column=1)

        self.root.mainloop()


Button()

Advertisement

Answer

How about this? You will have to rearrange it in the class ’cause I couldn’t fit it in, but works for me

from tkinter import *

def press_btn():
    btn.grid_forget()
    lbl = Label(root, text="label", width=15)
    lbl.grid(row=1, column=1)

root = Tk()
root.title("Button program")
root.geometry("100x100")

frame = Frame(root)

btn = Button(root, text="button", width=15, command=press_btn)
btn.grid(row=1, column=1)

root.mainloop()
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement