Home Ask Login Register

Developers Planet

Your answer is one click away!

Juan Dougnac February 2016

Destroying widget in tkinter

I am a beginner programmer, self-taught. I have managed to get a widget to appear by calling a function, then make it disappear by using the destroy method.

Unfortunately, the only way I managed to do that is by making the object global, which I understand is a bad way of doing things. I have tried several times to destroy the object without using global, but none of them worked.

Here's the relevant code:

def hayHijos():
    if z==1:
        var10 = StringVar()
        global numHijosMat
    elif z==0:
var9 = IntVar()
hijosEntrePartes = Checkbutton(app, text="Hijos entre las partes", variable=var9, command=hayHijos)


R4PH43L February 2016

Two general possibilities.

  • Either you create a class context to keep track of elements such as widgets using class variables (self.widget for example). Therefor have a look at the class documentation
  • You return and pass the widget to / from your function.

    This is not very suitable for callbacks but a general approach

    def function(var, widget=None):
        """ Widget is an optional argument. If not passed, it is initialized with None """
        if var.get()==1:
            # some code to create your widget
            # make sure to use 'widget = ...' to create it 
            # to have the reference for your return 
            # call at the end of the function
            # some code to destroy your widget
            # e.g. widget.destroy()
        return widget

    Using this code makes it easy for you to use the widget without making it global. Another variable is used in a global behaviour in your code. "var9". You should also pass this one on. You would need to adapt your callback using maybe a lambda to pass both. More recommended would be the class approach over here as lambdas often lack in scope of readability of code and reusability of code. (Could call it also "bad habit" but IMHO this is highly influenced by use case)

If you want to reuse the widget and only want to make it appear / disappear as the use of a Checkbutton suggests, I would rather recommend grid_remove method instead of widget.destroy method

Post Status

Asked in February 2016
Viewed 2,506 times
Voted 11
Answered 1 times


Leave an answer

Quote of the day: live life