Problem with packing widget in another window

51 Views Asked by At

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
2

There are 2 best solutions below

0
Robert Salamon On BEST ANSWER

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.

0
Сергей Кох On

To place terminal in Toplevel, you need to explicitly specify master, by default widgets have root parent.

import tkinter as tk
from tkterminal import Terminal
from functools import partial


def open_terminal():
    root.withdraw()

    cmd = tk.Toplevel(root)
    cmd.title("Terminal")
    cmd.protocol("WM_DELETE_WINDOW", partial(on_closing, cmd))
    
    terminal = Terminal(cmd, pady=5, padx=5)
    terminal.basename = "dolphinwriter$"
    terminal.shell = True
    terminal.pack(side="top", fill="both", expand=True)


def on_closing(cmd):
    cmd.destroy()
    root.deiconify()


root = tk.Tk()

btn = tk.Button(root, text="new_window", fg="Black", command=open_terminal)
btn.pack()

root.mainloop()