简体   繁体   中英

Destroying widget in tkinter

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()

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.

     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 # eg 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM