How do I quit a window in tkinter without quitting program? [duplicate]

試著忘記壹切 提交于 2019-12-11 15:38:21

问题


I would like the second 'Enter' button to allow the user to quit from this window. What is the command? I believe self.quit quits everything but the command I've used doesn't work.

import tkinter as tk

class Enter_Name_Window(tk.Toplevel):
    '''A simple instruction window'''
    def __init__(self, parent):
        tk.Toplevel.__init__(self, parent)
        self.text = tk.Label(self, width=40, height=2, text= "Please enter your name and class." )
        self.text.pack(side="top", fill="both", expand=True)

        enter_name = Entry(self)
        enter_name.pack()
        enter_name.focus_set()


        def callback():
            self.display_name = tk.Label(self, width=40, height=2, text = "Now please enter your tutor group.")
            self.display_name.pack(side="top", fill="both", expand=True)
            tutor = Entry(self)
            tutor.pack()
            tutor.focus_set()
            Enter_0.config(state="disabled")

            Enter_0_2 = Button(self, text="Enter", width=10, command=Enter_Name_Window.quit)
            Enter_0_2.pack()

        Enter_0 = Button(self, text="Enter", width=10, command=callback)
        Enter_0.pack()

回答1:


There were a lot of bugs to begin with and most notably:

command=Enter_Name_Window.quit

should be

command=self.destroy

Refrain from using the quit() method as its unstable and pass the class instance self instead of a new class object

Anywhere here's your revamped code:

class Enter_Name_Window(tk.Toplevel):
    '''A simple instruction window'''
    def __init__(self, parent):
        tk.Toplevel.__init__(self, parent)
        self.parent = parent
        self.text = tk.Label(self.parent, width=40, height=2, text= "Please enter your name and class." )
        self.text.pack(side="top", fill="both", expand=True)

        enter_name = tk.Entry(self)
        enter_name.pack()
        enter_name.focus_set()


        def callback():
            self.display_name = tk.Label(self.parent, width=40, height=2, text = "Now please enter your tutor group.")
            self.display_name.pack(side="top", fill="both", expand=True)
            tutor = tk.Entry(self.parent)
            tutor.pack()
            tutor.focus_set()
            Enter_0.config(state="disabled")

            Enter_0_2 = tk.Button(self.parent, text="Enter", width=10, command=self.destroy)
            Enter_0_2.pack()

        Enter_0 = tk.Button(self.parent, text="Enter", width=10, command=callback)
        Enter_0.pack()


来源:https://stackoverflow.com/questions/20547722/how-do-i-quit-a-window-in-tkinter-without-quitting-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!