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():
    print("ii")
    z=var9.get()
    if z==1:
        var10 = StringVar()
        global numHijosMat
        numHijosMat=OptionMenu(app,var10,1,2,3,4,5,6,7,8,9,10)
        numHijosMat.grid(column=2)
    elif z==0:
        print("aa")     
        numHijosMat.destroy()
var9 = IntVar()
hijosEntrePartes = Checkbutton(app, text="Hijos entre las partes", variable=var9, command=hayHijos)
hijosEntrePartes.var=var9
hijosEntrePartes.grid()

Answers


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
        else:
            # 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

Search




Leave an answer