Popup window with input entry in Tkinter

In this tutorial, we will learn how to take the input entry through a popup window using the Tkinter framework in Python.

Input entry in Tkinter – Python

As I have mentioned in my earlier posts, the first step in implementing any functionality is to have a clear step-by-step approach. In our case, we have to create a popup window from where we will take our input, and then after submitting, it will be displayed in the main window.

  • First, we have to create our main window using tk.Tk(). In it, create a button that will open the popup window.
  • Now, we need a variable to store the input and a label to display the output.
  • Create a user-defined function open_popup() to create a new window known as a popup window. In this window, we want our input text widget and a button to submit the input. We can create our input text widget using tk.Entry() and button from tk.Button().
  • The last thing is to display the entered text on the main window. So, let’s create a separate function show_entry_in_main(). We will add the following functionality: Storing the entered text and closing the popup window. This function will be called when we click on the submit button.

Code

import tkinter as tk

def show_entry_in_main():
    # Updating the label in the main window with the entry from the popup
    entry_text.set(entry.get())
    popup.destroy()  # This will close the popup window

def open_popup():
    global popup, entry
    popup = tk.Toplevel(root)  # Creating a popup window which will be on top of the main window
    popup.title("Input Entry")
    popup.geometry("300x150")

    # Input widget in the popup window
    entry = tk.Entry(popup)
    entry.pack(pady=(20, 10))

    # Submit button that will call the show entry function which will set the text to the variable
    btn_ok = tk.Button(popup, text="Submit", command=show_entry_in_main)
    btn_ok.pack()

# Creating the main window
root = tk.Tk()
root.title("Main Window")
root.geometry("400x300")

# Variable to store the input text
entry_text = tk.StringVar()

# Label to display the entry from the popup window
label = tk.Label(root, textvariable=entry_text)
label.pack()

# Button in the main window to open the popup window
btn_open_popup = tk.Button(root, text="Open Popup", command=open_popup)
btn_open_popup.pack()


root.mainloop()

Output

TKinter popup

Popup window with input entry in Tkinter

take input from popup input in Tkinter

Leave a Reply

Your email address will not be published. Required fields are marked *