How to create a child window and communicate with parents in Tkinter?

PythonTkinterServer Side ProgrammingProgramming

Unlike other Python libraries, Tkinter has many features that are used to create a full-fledged application. It supports multiple window operations and threading for processing the operation on Windows.

Following the thread, we will create an application that will pull the data from root window and put it into a child window. The concept of child window can be referred to as Dialog Boxes which present some information to the user during the happening of an event. The child window in Tkinter is created very easily by using Toplevel(root) constructor.

Example

In this example, we will create an entry widget along with a button in the main window. Further, the data stored in the entry widget will be pulled by a button that displays the input value in a new window or child window.

#Import tkinter library
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter frame or window
win= Tk()
#Set the geometry of tkinter frame
win.geometry("750x250")
win.title("Main Window")
#Define a function to Open a new window
def open_win():
   child_win= Toplevel(win)
   child_win.title("Child Window")
   child_win.geometry("750x250")
   content= entry.get()
   Label(child_win, text=content, font=('Bell MT', 20, 'bold')).pack()
   win.withdraw()
#Create an Entry Widget
entry=ttk.Entry(win, width= 40)
entry.pack(ipady=4,pady=20)
#Let us create a button in the Main window
button= ttk.Button(win, text="OK",command=open_win)
button.pack(pady=20)
win.mainloop()

Output

When we execute the above code, it will show a window with an entry widget and a button to open a new window.

Write something in the entry widget and click the OK button,

raja
Published on 22-Apr-2021 07:06:23
Advertisements