Luke ha scritto:
Hello, I'm an inexperienced programmer and I'm trying to make a
Tkinter window and have so far been unsuccessful in being able to
delete widgets from the main window and then add new ones back into
the window without closing the main window.

The coding looks similar to this:

...


It may just be bad coding but either way I could use some help.

Thanks


I fixed your code to do what you want, although I have no idea why you want it...

The main change is that you need to place the code to be executed when the button is clicked in a different function, and use the name of that function as value of the on_command property of the button. Then you need to give back the control to Tkinter, calling the mainloop function
and when the button is clicked, your function is called.
This sort of ping-pong is called event-driven programming, and it is how most GUI toolkit work. The functions called when a GUI event occurs are called callbacks.

A secondary thing is that since both the main function and the callback read and change some 'variable' pointing to the widgets, you need to share them using python 'global' statement. Now, a better way to do it would be incapsulate all in a class, but I wanted to stay as much as possible close to your code.

Finally, if you plan to to something that requires to dynamically create and destroy - or move arounds - graphical objects (not widgets), you might want to have a look to the 'Canvas' widget.

Code follows after signature. Since the frame and the button are recreated just after having been destroyed, you just see them flicker.

Ciao
----
FB


--------------------------------------------

#
# Module-level variables referring to widgets
# used/changed by more than one function
#
back_ground = None
frame1 = None


def make_frame_and_button():
    global frame1, back_ground
    print 'background', back_ground
    frame1=Frame(back_ground,width=213,height=480,bg='white')
    print 'Frame1',  frame1
    frame1.pack_propagate(0)
    frame1.pack(side=TOP,anchor=N)
    frame1.pack_propagate(0)
    frame1.pack(side=TOP,anchor=N)
    close_frame1=Button(frame1,text='close', bg='blue',
                        command=on_close_button )
    print 'close_frame1', close_frame1
    close_frame1.pack_propagate(0)
    close_frame1.pack(side=TOP, anchor=N,pady=25)


def on_close_button():
    global frame1
    frame1.destroy()
    make_frame_and_button()


def MainWin():
    global back_ground, frame1
    main=Tk()
    main.geometry('640x480')
    back_ground=Frame(main,width=640,height=480,bg='black')
    back_ground.pack_propagate(0)
    back_ground.pack(side=TOP,anchor=N)
    make_frame_and_button()
    main.mainloop()


MainWin()
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to