简体   繁体   中英

Python Tkinter application doesn't quit properly

from TKinter import *

class Ui(Frame):
  def __init__(self)
    Frame.__init__(self, None)

    self.grid()
    bquit=Button(self, text="Quit", command=self.quit_pressed)
    bquit.grid(row=0, column=0)

  def quit_pressed(self):
    self.destroy()

app=Ui()
app.mainloop()

Why doesn't this Tkinter program end properly when I press the "Quit" button?

The reason this does not work is because you are using an incorrect way to end the program in quit_pressed. What you are doing right now is killing the self frame, not the root frame. The self frame is a new frame that you have gridded into the root frame, therefore when you kill the self frame, you are not killing the root frame. This may sound confusing due to my typing style, so let me give an example.

Currently, you have

def quit_pressed(self):
    self.destroy() #This destroys the current self frame, not the root frame which is a different frame entirely

You are able to remedy this by changing the function to this,

def quit_pressed(self):
    quit() #This will kill the application itself, not the self frame.

使用self.destroy()只是销毁Frame,而不是顶层容器,您需要执行self.master.destroy()才能正确退出

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM