Creating a popup message box with an Entry field in tkinter



Tkinter Popup are toplevel window interfaces that wrap up the widget and the element with the main window. It can be embedded in any main window using a handler like Button Widget. Popup can be created using the Toplevel(root) constructor.

Example

In this example, we will create a simple application containing a Label widget and a button to open the popup message box which contains an Entry field. Once the popup is opened, it can have the functionality to go back to the main window.

#Import the required library from tkinter import* #Create an instance of tkinter frame win= Tk() #Define geometry of the window win.geometry("750x250") #Define a function to close the popup window def close_win(top):    top.destroy() def insert_val(e):    e.insert(0, "Hello World!") #Define a function to open the Popup Dialogue def popupwin():    #Create a Toplevel window    top= Toplevel(win)    top.geometry("750x250")    #Create an Entry Widget in the Toplevel window    entry= Entry(top, width= 25)    entry.pack()    #Create a Button to print something in the Entry widget    Button(top,text= "Insert", command= lambda:insert_val(entry)).pack(pady= 5,side=TOP)    #Create a Button Widget in the Toplevel Window    button= Button(top, text="Ok", command=lambda:close_win(top))    button.pack(pady=5, side= TOP) #Create a Label label= Label(win, text="Click the Button to Open the Popup Dialogue", font= ('Helvetica 15 bold')) label.pack(pady=20) #Create a Button button= Button(win, text= "Click Me!", command= popupwin, font= ('Helvetica 14 bold')) button.pack(pady=20) win.mainloop()

Output

Running the above code will display a window that contains a button to open the Popup Dialogue.

Once we click the button, it will open the popup Dialog Box. The popup Dialog has two buttons, each for a different purpose. When we click the “Ok” button, it will destroy the popup and revert back to the main window.

Updated on: 2021-04-15T13:17:44+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements