I’d like an application that has two existing frames in a root, of which we only see one at a time, and which can be swapped for the other. The method to swap between them is to place one, and place_forget the other.
This following code reproduces the error. It involves just a button, and two frames (one red one green). The code has the red frame placed first, and the button has a command to perform the ‘swap’. When pressed, the red frame is removed, and the green frame is placed, as expected.
The error: For all subsequent presses, neither the red nor the green will appear, although the swap function still technically works (can be checked by introducing print commands in the if else blocks).
Note: if one removes the three lines of code mentioning the green frame ‘f1’, the bug in a sense vanishes, that is, the button removes and replaces the red frame without issue. It’s the introduction of an additional frame that seems to cause problems
import tkinter
root = tkinter.Tk()
f0 = tkinter.Frame(root, bg = 'red') # initialize + place first frame
f0.place(x=0, y=0, width = 100, height = 100)
f1 = tkinter.Frame(root, bg = 'green') # initialize second frame
def swap(): # define function that swaps frames
if f0.winfo_viewable(): # if f0 is displayed, place_forget f0 and place f
f1.place(x=0, y=0, width = 100, height = 100)
f0.place_forget()
else: # if f1 is displayed, place_forget f1 and place f0
f0.place(x=0, y=0, width = 100, height = 100)
f1.place_forget()
b = tkinter.Button(root, text = 'Change Frame', command = swap)
b.place(x=0, y=100)
root.mainloop()
I circumvented the problem in my code by simply overlapping the frames i.e. removing the ‘place_forget’ lines. So the issue is overcame, however, I’m still posing the question to see if my place_forget approach has a flaw, or if there is a bug in tkinter.