0

I have a program I'm working on where, to keep it in the same window, I have my widgets in a frame. When I want to change the window, then I use either frame.pack_forget() or frame.grid_forget() and then frame.destroy() before simply adding a new frame to the new window. However, even having used grid_forget, if I use .pack(), I get an error saying I can't use pack when something is already managed by grid. Does anyone know how to circumvent this while still keeping everything within the same window?

.pack_forget seems to be working fine as I can transition from a frame using pack to a frame using grid without issue.

Here is a reproduction of the problem:

from tkinter import *

root = Tk()


def main_Menu (root):
    frame = Frame(root)
    frame.pack()

    button = Button(frame, text="button ", command=lambda:[frame.pack_forget(), frame.destroy, function(root)])
    button.pack()

def function(root):
    frame = Frame(root)
    frame.grid(row=0)

    back_Button = Button(root, text="Back", command=lambda:[frame.grid_forget(), frame.destroy(), return_To_Menu(root)])
    back_Button.grid(row=0)

def return_To_Menu(root):
    main_Menu(root)

main_Menu (root)

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Gavin
  • 13
  • 2
  • Show us your code, please. – J_H Mar 28 '20 at 19:22
  • FWIW, you don't need to call any of the "forget" functions if you're following that by destroying the widgets. Please [edit] your question to include a [mcve]. If you're getting the error you say you do, there almost certainly is another window being managed by `grid`. The "circumvention" you're asking about is to not use both `pack` and `grid` for widgets that have the same master. – Bryan Oakley Mar 28 '20 at 19:23
  • Okay, my minimal reproducible example has been added. – Gavin Mar 28 '20 at 19:46
  • Read up on [Tutorial - 9.2. Python Scopes and Namespaces](https://docs.python.org/3/tutorial/classes.html#scopes-and-namespaces-example) and [Python and Tkinter lambda function](https://stackoverflow.com/a/11005426/7414759) – stovfl Mar 28 '20 at 19:55

1 Answers1

1

Your packed Button is attached to the frame, while the grided button is attached to the root.

After changing

    back_Button = Button(root, text="Back", command=lambda:[frame.grid_forget(), frame.destroy(), return_To_Menu(root)])
    back_Button.grid(row=0)

to

    back_Button = Button(frame, text="Back", command=lambda:[frame.grid_forget(), frame.destroy(), return_To_Menu(root)])
    back_Button.grid(row=0)

it worked for me.

Thomas H.
  • 49
  • 4