Python Tkinter 关闭 Windows

Python Tkinter Closing Windows

在创建 Python Tkinter 程序时,我希望创建一个关闭程序的按钮。我试过

#with master = Tk()
master.quit()

方法。它对我的程序绝对没有任何作用——除了停止任何工作,尽管我没有收到任何回溯。

我试过的另一种方法是:

#with master = Tk()
master.destroy()

这又对我的程序没有任何作用 - 它确实给了我一个回溯错误,尽管它是:

_tkinter.TclError: can't invoke "button" command: application has been destroyed

我的完整代码是:

from tkinter import *
master = Tk()

exitbutton = Button(master,text="Exit",(all the other personalization stuff here),command=(master.quit())) 
#or I used master.destroy() in the command area.
exitbutton.grid(column=0,row=0)

None以上方法均有效

非常感谢 (为了未来)

您想将一个函数对象传递给命令关键字,所以不要使用括号。你也应该使用 TKinter 的 destroy 函数。

exitbutton = Button(master,text="Exit",(all the other personalization stuff here),command=master.destroy) 

您必须传递函数的名称而不是作为可调用函数:

from tkinter import *
master = Tk()

exitbutton = Button(master,text="Exit",command=master.destroy)##dont include the parentheses
##or I used master.destroy() in the command area.
exitbutton.grid(column=0,row=0)

这应该可以解决您的问题。

问题:

  • 唯一的问题是您在将函数(exitdestroy)作为 command 传递给 Button 时使用括号() , 这导致它在定义的地方执行。

解法:

  • 解决方案是在将函数(exitdestroy)作为 command 传递给 Button 时删除括号()

固定代码:

from tkinter import *

master = Tk()

exitbutton = Button(master, text="Exit", command=master.quit)   # you can also use master.destroy
exitbutton.grid(column=0, row=0)

master.mainloop()

提示:

  • 由于导入所有 (*) 不是一个好的做法,您应该 import tkinter as tk 或者你想要的任何东西。您要做的唯一更改是在属于 tkinter.
  • 的每个对象之前添加 tk.

那么你的代码如下。

最佳实践:

import tkinter as tk
master = tk.Tk()

exitbutton = tk.Button(master, text="Exit", command=master.quit)   # you can also use master.destroy
exitbutton.grid(column=0, row=0)

master.mainloop()