Search code examples
pythontkinter

can't create tkinter windows iteratively and wait to each response


I would like to create a tkinter window for each element in an array in order to choose a different name. The idea is to popup the windows one by one. However, when the first windows has already been destroyed (NEXT button pressed), the program gets stuck.

Here's the minimal executable code to run it:

import tkinter

root = tkinter.Tk()
root.title("FBTA-BATF")
root.geometry("900x420")
button_names = []
for file in ["/Hello", "/Bye"]:
    button_text_selector = tkinter.Tk()
    button_text_selector.title("Elige el texto del botón para...")
    button_text_selector.geometry("500x150")

    button_text_selector.columnconfigure(0, weight=1)
    button_text_selector.columnconfigure(1, weight=1)
    button_text_selector.columnconfigure(2, weight=1)

    file_name = file.split("/")
    file_name = file_name[len(file_name)-1]

    file_label = tkinter.Label(button_text_selector, text="Nombre del botón para: " + file_name)
    button_text_entry = tkinter.Entry(button_text_selector, width=65, disabledforeground="red")
    file_label.grid(row=0, column=1)
    button_text_entry.grid(row=1, column=1)

    def append_button_names():
        button_names.append(button_text_entry.get())
        button_text_selector.destroy()

    ok_button = tkinter.Button(button_text_selector, text='NEXT', command=append_button_names)
    ok_button.grid(row=2, column=1)

    root.wait_window(button_text_selector)


Solution

  • Tkinter is designed to have a single root (Tk()) window, and when the root window is destroyed, the program exits. Because of that, the solution is to use instances of Toplevel for your popup windows.

    for file in ["/tmp/Hello", "/tmp/Bye"]:
        button_text_selector = tkinter.Toplevel()
        ...