Search code examples
pythontkintertk-toolkitpack

Problem with packing widget in another window


I have a problem, I need to on button clicking pack terminal from tkterminal library in new window and destroy it(like toggle), but terminal is packing in already exists "root" window, so there is a code:

def open_terminal():
    global debounce
    if debounce == True:
        global cmd
        cmd = tk.Toplevel(root)
        cmd.title("Terminal")
        global terminal
        terminal = Terminal(pady=5, padx=5)
        terminal.basename = "dolphinwriter$"
        terminal.shell = True
        terminal.pack(cmd, side="top", fill="both", expand=True)
        debounce = False
        print(debounce)
    else:
        cmd.destroy()
        debounce = True

I'm trying this:

  1. Checking if already terminal packed in root window and if yes, unpack it and pack it again
  2. Upacking terminal and pack it again without checking. I tried to do everything described above with the pack_forget() method

Solution

  • The problem is that you defined the terminals master window in the line where you pack it: terminal.pack(cmd, side="top", fill="both", expand=True).

    In Tkinter, assigning the master window is done when you create the object.

    Corrected code:

    def open_terminal():
        global debounce
        if debounce == True:
            global cmd
            cmd = tk.Toplevel(root)
            cmd.title("Terminal")
            global terminal
            terminal = Terminal(master=cmd, pady=5, padx=5)
            terminal.basename = "dolphinwriter$"
            terminal.shell = True
            terminal.pack(side="top", fill="both", expand=True)
            debounce = False
            print(debounce)
        else:
            cmd.destroy()
            debounce = True
    

    Should fix it.