2021-05-30

How to get the updated entry string from a toplevel window before the tkinter main loop ends?

I have a toplevel window that pops up and asks you for your name. When you enter your name and click ok it should put the name in the entry1_value and close itself. Then I print the variable while keeping the empty (in this snippet of code) main window running. The problem is that it prints the 'Empty String' on the first print and then only the input on the second one.

Here I'm just printing the information so I see if it registers it but I will use it somewhere later.

Also, in reality I just need the updated information placed outside in any way without the main window closing.

Here is the code:

import tkinter as tk
from tkinter import ttk

BUTTON_FONT = ('Lato', 16)

class NameInputBox:
    entry1_value = 'Empty String'
    def __init__(self, text):
        
        self.window = tk.Toplevel()
        self.window.wm_title("Input Name.")

        self.label_message = tk.Label(self.window, text = text, font = (BUTTON_FONT, 20))

        self.frame1 = ttk.Frame(self.window)
        self.entry1 = ttk.Entry(self.frame1, font = BUTTON_FONT, width = 10)
        self.button_message = ttk.Button(self.frame1, text="Ok", command = lambda: self.name_input_box_exit(self.window))
        
        self.entry1.pack(side = 'left', padx = 5, pady = 5)
        self.button_message.pack(side = 'left', pady = 5, padx = 5)

        self.label_message.pack(side = 'top', pady = 10, padx = 10)
        self.frame1.pack(side = 'bottom', pady = 10, padx = 10)


    def name_input_box_exit(self, window):
        self.entry1_value = self.entry1.get()
        self.entry1.delete(0,tk.END)

        self.window.destroy()    

box1 = NameInputBox('Input the Name:')

print(box1.entry1_value)
tk.mainloop()
print(box1.entry1_value)

Thank you for your help!



from Recent Questions - Stack Overflow https://ift.tt/2RNUrda
https://ift.tt/eA8V8J

No comments:

Post a Comment