1

The problem (Story):

I write inside an entry widget, then I press a button and a new label appear in the window with the text that I have entered. Then I press a different button and the expecting result is that the generated label disappear but, I receive an error message.

Why do I want to do this?

I want to make an interface to make SQL queries, the process that I'm trying to implement is:

  • The user enters a string in an entry widget.
  • The user presses a "search" button to perform the query.
  • The interface returns the results. (I have achieved this using LabelFrame and Frame widgets).
  • The user presses a "clear" button and all the widgets generated disappear and the interface is ready for a new query.

The label that doesn't hide(code):

from tkinter import *

root = Tk()

pacienteLabel = Label(text="Paciente: ")
pacienteLabel.grid()

pacienteEntry = Entry()
pacienteEntry.grid()

profesionalLabel = Label(text="Profesional: ")
profesionalLabel.grid()

profesional = StringVar()
# Here I capture the string that I want to show:
profesionalEntry = Entry(textvariable=profesional)
profesionalEntry.grid()

def ver():
    # This label is generated without problems: 
    newLabel = Label(text="hola profesional: {}".format(profesional.get()))
    newLabel.grid()
    # When I was trying to figure out what was happening I added this:
    print(newLabel)
    # And the output is:
    # .!label4 
    # I have read through documentation why is this but I couldn't find why.


buscarButton = Button(text="Buscar", command=ver)
buscarButton.grid()


def borrar():
    # After that I saw the previous output from print was obvious why the
    # next line don't work:
    newLabel.grid_forget()

borrarButton = Button(text="Borrar", command=borrar)
borrarButton.grid()

root.mainloop()

The following picture shows the error and the GUI:

Error & GUI

In the end, what have I read here:

Finally if you are reading this question, thanks for your time!

2
  • Why do you hide as opposed to destroying?
    – Nae
    Mar 10, 2018 at 15:39
  • How exactly is the title in 3rd or 5th revision the better one grammatically?
    – Nae
    Mar 10, 2018 at 20:15

1 Answer 1

0

You can add global newLabel as the first line to def ver(): but that would let you only hide the very last label you've created, unrecursively. The reason for that is that you have no reference left for the former label objects, but they still exist, but they cannot exactly easily be referenced. Instead, I'll provide an answer that answers:

"How to hide a label that was generated with a command button, using another button?"

One can do all kinds of things to a widget(label is a widget) so long as they have a valid reference(your newLabel reference gets overwritten). It doesn't matter how they are created, so long as they have the reference. In the example below, there's a button_that_creates_labels, a button_that_hides_labels, an entry that lets the user set the new label's text. The button_that_hides_labels hides the last label added, recursively:

try:                        # In order to be able to import tkinter for
    import tkinter as tk    # either in python 2 or in python 3
except ImportError:
    import Tkinter as tk


def create_new_label(parent, widget_list, entry, button):
    widget_list.append(tk.Label(parent, text=entry.get()))
    widget_list[-1].grid(columnspan=2)
    button['command'] = lambda w=widget_list, i=-1, b=button: \
        hide_the_last_label(w, i, b)


def hide_the_last_label(widget_list, index, button):
    if len(widget_list) >= abs(index):
        widget_list[index].grid_remove()
        button['command'] = lambda w=widget_list, i=index-1, b=button: \
            hide_the_last_label(w, i, b)


def main():
    root = tk.Tk()
    # This list will contain all widgets objects generated during the
    # execution of the lambda expression.
    labels = list()
    entry = tk.Entry(root)
    button_that_hides_labels = tk.Button(root, text="Hide")
    # A lambda expression to prevent call the function before the
    # button has been pressed.
    button_that_creates_labels = tk.Button(root, text="Create",
        command=lambda p=root, wl=labels, e=entry, b=button_that_hides_labels\
                                            : create_new_label(p, wl, e, b))
    button_that_hides_labels['command'] = lambda w=labels, i=-1, \
                    b=button_that_hides_labels:hide_the_last_label(w, i, b)
    button_that_creates_labels.grid(row=1, column=0)
    button_that_hides_labels.grid(row=1, column=1)
    entry.grid(row=0, column=0, columnspan=2)
    tk.mainloop()

if __name__ == '__main__': main()

However, if you wanted to destroy & delete instead of just hiding, my implementation would've been much simpler:

try:                        # In order to be able to import tkinter for
    import tkinter as tk    # either in python 2 or in python 3
except ImportError:
    import Tkinter as tk


def create_new_label(parent, widget_list, entry):
    widget_list.append(tk.Label(parent, text=entry.get()))
    widget_list[-1].grid(columnspan=2)


def remove_the_last_label(widget_list):
    if widget_list:
        # Here the widget don't show up
        widget_list[-1].destroy()
        # If the item is not removed from the list, white spaces will remain
        # in the window.
        del widget_list[-1]


def main():
    root = tk.Tk()
    labels = list()
    entry = tk.Entry(root)
    button_that_hides_labels = tk.Button(root, text="Hide")
    button_that_creates_labels = tk.Button(root, text="Create",
        command=lambda p=root, wl=labels, e=entry: create_new_label(p, wl, e))
    button_that_hides_labels['command'] = lambda w=labels: \
                                                    remove_the_last_label(w)
    button_that_creates_labels.grid(row=1, column=0)
    button_that_hides_labels.grid(row=1, column=1)
    entry.grid(row=0, column=0, columnspan=2)
    tk.mainloop()

if __name__ == '__main__':
    main()
2
  • your solution worked perfect. I will add some comments to your code just for clarifying and check if I understood well how the code works. I have to ask, where can I find more info about "objects references" in "tkinter or working with callbacks in tkinter"? I have found many "follow this recipe in tkinter" but no many articles that explain how the things works. In a few days I will post a repo in github with my "db browser gui".
    – Venguiat
    Mar 12, 2018 at 18:37
  • @Venguiat Object references and callbacks can be read about Python as well. They're not specific to tkinter. You may want to read about callbacks for tkinter here perhaps.
    – Nae
    Mar 12, 2018 at 18:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.