簡體   English   中英

為什么 destroy() 方法在我的 tkinter 程序中不起作用?

[英]Why destroy() method doesn't work in my tkinter program?

為什么,當我使用 destroy() 方法時,程序沒有關閉? 我嘗試使用 Nick.destroy()、root.destroy() 和 self.destroy(),但它們都不起作用。 當用戶輸入正確的昵稱並將其傳遞出 class 時,嘗試關閉 window

from tkinter import *

class Nick(Frame):
    def __init__(self, master):
        super(Nick, self).__init__(master)
        self.master = master
        self.grid()
        self.mes = None
        self.count = 0
        self.lbl = Label(self, text="WPROWADZ NICK").grid(row=1, column=1)
        self.ent =Entry(self)
        self.ent.grid(row=2, column=1)
        btn = Button(self, text="Akceptuj", command=self.accept)
        btn.grid(row=2, column=2)
        self.error = Label(self, text="")
        self.error.grid(row=3, column=1)

    def accept(self):
        self.mes = self.ent.get()
        if len(self.mes) == 0:
            self.error.config(text="Nick nie moze byc pusty")
        elif " " in self.mes:
            self.error.config(text="Nick nie moze zawierac spacji")
        else:
            global mes
            mes = self.mes
            Nick.destroy()
        if self.count == 0:
            self.error.config(text="")
            self.count+=1

def main_tk():
    root = Tk()
    root.title("ONLINE CHAT")
    root.geometry("260x100")
    app = Nick(root)
    root.mainloop()

main_tk()
print(mes)

最快的解決方法是將Nick.destroy()替換為self.master.destroy()

這就是您嘗試過的那些不起作用的原因:

  • Nick.destroy() : Nick class 沒有名為destroy的@classmethod
  • root.destroy()root只能在 main 方法中訪問,並且.mainloop是阻塞的。 因此,當您退出主循環時(通過關閉程序,ctrl + c 等),無需銷毀根。
  • self.destroy() :銷毀Nick class 只會銷毀它繼承的Frame ,因此不會關閉整個程序

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM