![](/img/trans.png)
[英]How to close a single window in Tkinter without closing the main window?
[英]Python Tkinter - Close dialog without closing main window
我正在尝试使用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()
运行此命令时,我会得到一个对话框和一个主窗口,但问题是当我关闭对话框时,主窗口也会关闭。 对话框关闭时,我希望主窗口保持打开状态,有人可以帮我吗?
在Windows中添加标题,您会看到
您将Entry
添加到MainWindow
。
然后关闭MainWindow
但您认为它是TextEntryDialog
。
您必须在Entry
添加self.top
( Toplevel
)作为parent
,以将其放入正确的窗口中。
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()
您可能需要重组代码。 下面的示例应用程序演示了如何打开一个用于输入文本的对话框以及如何在对话框执行完后防止关闭主窗口:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.