1
votes

I'm trying to make a text entry dialog with Tkinter (Python 3.5) but I'm having some problems. This is my code:

class TextEntryDialog:
    def __init__(self, master):
        self.top = Toplevel(master)
        self.textField = Entry()
        self.textField.pack()

root = Tk()
ted = TextEntryDialog(root)
root.mainloop()

When I run this I get a dialog and a main window just like I want, but the problem is that when I close the dialog the main window closes as well. I would like the main window to stay open when the dialog closes, can anyone help me with this?

2
How are you closing the dialog? If you do ted.destroy() it shouldn't close the main window. - Bryan Oakley
you get something different you think - MainWindow is a window which you think is TextEntryDialog. You add Entry to MainWindow because you didn't use parent in Entry. And you close MainWindow but you think you close TextEntryDialog - furas

2 Answers

1
votes

Add titles to windows and you see

enter image description here

You add Entry to MainWindow.
And you close MainWindow but you think it is TextEntryDialog.

You have to add self.top (Toplevel) as parent in Entry to put it in correct window.

self.textField = Entry(self.top)

.

from tkinter import *

class TextEntryDialog:
    def __init__(self, master):
        self.top = Toplevel(master)
        self.top.title("TextEntryDialog")

        self.textField = Entry(self.top) # parent
        self.textField.pack()

root = Tk()
root.title("MainWindow")
ted = TextEntryDialog(root)
root.mainloop()
0
votes

You may want to restructure your code. The following sample application demonstrates how to open a dialog for text entry and prevent closure of the main window when the dialog finishes executing:

from tkinter import Label, NoDefaultRoot, Tk
from tkinter.font import Font
from tkinter.simpledialog import askstring


def main():
    NoDefaultRoot()
    root = Tk()
    root.title('Demonstration')
    root.resizable(False, False)
    Label(root, font=Font(root, size=24)).grid()
    root.after_idle(animate_label, root, 3)
    root.mainloop()


def animate_label(root, time_left):
    label = get_any_child(root, Label)
    label['text'] = 'Opening a dialog in {} ...'.format(max(time_left, 0))
    if time_left > 0:
        root.after(1000, animate_label, root, time_left - 1)
    else:
        root.after_idle(open_dialog, root)


def get_any_child(widget, kind):
    return get_any(get_children(widget), kind)


def get_children(widget):
    return iter(widget.children.values())


def get_any(iterable, kind):
    return next(item for item in iterable if isinstance(item, kind))


def open_dialog(root):
    answer = askstring('Text Entry', 'Who are you?', parent=root)
    label = get_any_child(root, Label)
    if answer:
        label['text'] = 'You are {}.'.format(answer)
    else:
        label['text'] = 'I must find out who you are.'
        root.after(3000, open_dialog, root)

if __name__ == '__main__':
    main()