How to embed a Tkinter GUI into another Tkinter GUI?

67 views Asked by At

This is my first GUI:

#GUI1
import random, Id_generator, tkinter as tk
from tkinter import ttk

#constanst
STUDENTS = 15
TEACHERS = 4

def main():
    #Main Window
    app = tk.TK()
    app.title('GUI1')
    app.geometry('1000x600')
    
    more code here...

    app.mainloop()
  

def other_function()
    code...

This is my second GUI2

#GUI2 
import GUI1, tkinter as tk, 
from tkinter import ttk

#window
app = tk.Tk()
app.title('GUI2')
app.geometry('1400x800')

label_1 = ttk.Label(app, text ='imported gui')
label_1.pack()
gui_frame = tk.Frame(app)
gui_frame.pack(expand = True, fill = 'both')

gui_1_instance = GUI1.main()
gui_1_instance.pack(in_ = frame, expand = True, fill = 'both'

I want to embed GUI1 into GUI2, so that when I run GUI2, GUI1 will display within GUI2's window. This is what I've tried so far: change the app.mainloop() statement in GUI1 for return(app). I've had no success so far. Whenever I run GUI2 two windows open GUI1 and GUI2, but GUI1 doesn't get packed into GUI2.

How can I embed a GUI within a GUI? Is this possible with Tkinter? or should I switch to PYQT?

2

There are 2 answers

2
Suramuthu R On

Embedding a tkinter GUI into another tkinter GUi is very easy. As your code is not complete, I'm showing here with another example.

from tkinter import *


#GUI to be embedded
def embed_gui(parent):
    
    frame = Frame(parent)
    frame.pack(side='top')


    label = Label(frame, text="This is the embedded GUI")
    label.pack(side='top')
    
    btn = Button(frame, text="Submit")
    btn.pack(side='top')



#GUI in which embedded into
def main():
    root = Tk()
    root.geometry('500x400')

    # Embed using the function embed_gui
    embed_gui(root)

    root.mainloop()

#run main() if main is the main function and not the imported one.

if __name__ == "__main__": main()
    
0
acw1668 On

You can embed a window inside a frame with the following changes:

  • set container=True when creating the frame gui_frame
  • set use=gui_frame.winfo_id() on the window which to be embedded

GUI1:

import tkinter as tk

def main():
    app = tk.Tk()
    app.title('GUI1')
    app.geometry('1000x600')
    app.config(bg="pink")

    tk.Label(app, text="Hello World", bg="pink").pack(padx=20, pady=20)

    return app  # return the window

GUI2:

import tkinter as tk
from tkinter import ttk
import GUI1

app = tk.Tk()
app.title('GUI2')
app.geometry('640x480')

label_1 = ttk.Label(app, text ='imported gui')
label_1.pack()

gui_frame = tk.Frame(app, container=True)  # set container=True
gui_frame.pack(expand=True, fill='both', padx=10, pady=10)

gui_1_instance = GUI1.main()
gui_1_instance.config(use=gui_frame.winfo_id()) # set use=...

app.mainloop()

Result:

enter image description here

Note that it is better to use Toplevel for the embedded window to avoid using multiple instances of Tk.