r/pythonhelp • • Mar 07 '20

tkinter Frame object destroyed after place_forget() - how to conserve?

TLDR: I want to show/hide frame objects, that are dictionary elements, without them being destroyed. Defining the dict as a global doesn't work. Please help.

Code: https://pastebin.com/nJRVSVSV

Hi guys,

I have a tkinter program to input some user data, I want to be able to show either 2 or 4 frames at a time, with a 'Name' input box, and for the names to be conserved when the number of frames is updated.

My tkinter objects are stored in a dictionary and I'm using place() and place_forget() to show and hide the frames.

My problem is that when I show/hide the frames, the data inside them is lost.

I have already solved a similar problem with an image, in that case I put the image object/tk canvas as globals variables so that it wasn't deleted in the garbage collection when I hid the image.

I can't seem to make this approach work this time.

I have set the frames_dict as a global variable, but I feel like the frame objects that are the individual elements of the dictionary are not globals, so are being destroyed by garbage collection. This is confirmed print the frame object IDs as they are shown/hidden.

How can I set the individual frames as global variables so that they are not destroyed?

Is there another approach? If possible I would like to avoid the use of globals.

Thanks!

3 Upvotes

2 comments sorted by

2

u/sentles Mar 07 '20

There are various things to note here. Firstly, the reason why the frames are being remade is because you call the place_frame function every time the user chooses a different option (2 or 4). That function creates new Tkinter objects (new frame, new label, new entries) whenever it is called. These new objects overwrite the dictionary values, instead of just showing the old frames.

I also agree with you that you should avoid using globals. Something that I'm not sure you quite understand is the function of return: when a function returns a value, that value will be placed in any expression that contains a call to that function. If a function doesn't return a value, it returns None by default. In your code, you return values in two different functions, initialise_frames and place_frame. However, in all your calls to those two functions, you never save or use those return values anywhere. Therefore, those returns are useless. Read up on this for more on return.

Initially, I would argue that since the place_frame function creates the frames, it should only be run once. Therefore, it doesn't have to be a function of its own; it's code can be integrated with the initialise_frames function. You can get rid of the place_frame function. Also, since we later want to be able to "remember" the frames, we need their positions. For this reason, the format {number: (frameObj, (x, y))} can be used for the dictionary instead of just {number: frameObj}. In this way, the dictionary doesn't just save the frame, but also its position (which will be needed to "remember" the frame). Therefore:

def initialise_frames(first_corner_x,first_corner_y,w,h,x_pad,nb_frames):
    '''
    Initialises all 4 frames
    '''
    frames_dict={}

    '''
    Places an individual frame frame in the correct position
    '''
    for i in range(1,nb_frames+1):

        frame_dict = tk.Frame(width=w,height=h,relief='groove',borderwidth='2')

        frame_x=first_corner_x+w*(i-1)+x_pad*(i-1)    #horizontal position increases by width+pad for each i
        frame_y=first_corner_y                        #vertical position doesn't change


        frame_dict.place(x= frame_x,y= frame_y)

        frames_dict[i] = (frame_dict, (frame_x, frame_y)) #value is now a tuple containing the object, and the position

        current_frame=frames_dict[i][0]

        title_text= 'Frame ' + str(i)

        frame_label=tk.Label(current_frame,text=title_text,anchor="w")
        frame_label.place(x=2,y=2)

        frame_name_label=tk.Label(current_frame,text='Name',anchor="w")
        frame_name_label.place(x=2,y=35)

        frame_name_entry = tk.Entry(current_frame,width=15,bg="white")
        frame_name_entry.place(x=45,y=35)

        print (' i=',i,'  Frame object:', frames_dict[i][0])

    return frames_dict

The return statement here will be necessary, because we'll need to save that dictionary and be able to pass it to hide_frames, as well as a new function we'll make, show_frames.

Initially, you call hide_frames by default. To avoid the use of globals, we pass frames_dict as an argument to hide_frames:

def hide_frames(frames_dict):
    '''
    Hides frame frames 3 and 4
    '''
    for i in [3,4]:

        frames_dict[i][0].place_forget()

        print (' i=',i,'  Frame object:', frames_dict[i][0])

Notice that we now refer to the frame object as frames_dict[i][0]. This is because frames_dict[i] is a tuple, containing the actual frame at position 0 and its position on your window at position 1.

And then, below:

frames_dict = initialise_frames(first_corner_x,first_corner_y,w,h,x_pad,4)
hide_frames(frames_dict)

Now, because frames_dict isn't global, we will bind the NbframesSelected function to the Combobox after the call to initialise_frames. This way, we can use lambdas to pass it as an argument to NbframesSelected:

combo_nb_frames.bind("<<ComboboxSelected>>", lambda x: NbframesSelected(x, frames_dict))

Another function that is needed is a show_frames function, which will be called when the user selects the 4 option to show the hidden two frames. This is quite simple to do; we have the frame object inside the dictionary, as well as their positions. All we have to do is place them in their respective positions:

def show_frames(frames_dict):
    '''
    Shows frames 3 and 4
    '''
    for i in [3, 4]:

        frames_dict[i][0].place(x = frames_dict[i][1][0], y = frames_dict[i][1][1])

Since frames_dict[i] is a tuple, we're essentially placing frames_dict[i][0] (the frame object) at x = frames_dict[i][1][0] and y = frames_dict[i][1][1]. Since frames_dict[i][1] is the position, then frames_dict[i][1][0] is the x position and frames_dict[i][1][1] is the y position (we saved them as (x, y)).

Finally, since the make_frame_frame function is also unnecessary, we'll integrate its code with the NbsframesSelected function, which now takes frames_dict as a parameter:

def NbframesSelected(event2, frames_dict):
    '''
    frame selection event
    '''
    nb_frames=int(combo_nb_frames.get())
    '''
    Places / forgets the requested amount of frame frames
    '''
    if nb_frames==2:
        hide_frames(frames_dict) #hides frames 3 and 4
    elif nb_frames==4:
        show_frames(frames_dict)

And voila! When you now type something into, say, the name entry of frame 3, then choose the option 2, frame 3 disappears. But if you choose 4 again, making frame 3 appear, whatever was typed in its name entry is preserved. This same thing will apply to any other entries you might add later to those frames, of course.

The only thing I still don't like (though it's not a problem per se), is that the parameters for the frame position are global. However, you can easily fix that yourself; you could, for example, make a new dictionary called frame_params and pass that to initialise_frames. In any case; hope I helped.

The entire code on pastebin.

2

u/PelagiaNoctiluca Mar 07 '20

Wow! Thanks so much for this fantastic reply. Clear yet detailed and also incredibly helpful, I've learnt loads!