Python Tkinter - 关闭对话框而不关闭主窗口

时间:2016-01-27 17:45:35

标签: python tkinter

我正在尝试使用Tkinter(Python 3.5)创建一个文本输入对话框,但我遇到了一些问题。这是我的代码:

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

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

当我运行这个时,我得到一个对话框和一个主窗口就像我想要的那样,但问题是当我关闭对话框时主窗口也会关闭。我希望主窗口在对话框关闭时保持打开状态,任何人都可以帮我这个吗?

2 个答案:

答案 0 :(得分:1)

向Windows添加标题,您会看到

enter image description here

您将Entry添加到MainWindow 然后关闭MainWindow,但您认为它是TextEntryDialog

您必须在self.top中将Toplevelparent)添加为Entry,才能将其置于正确的窗口中。

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()

答案 1 :(得分:0)

您可能需要重新构建代码。以下示例应用程序演示了如何打开文本输入对话框,并在对话框完成执行时阻止关闭主窗口:

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()