在创建Python Tkinter程序时,我希望创建一个将关闭该程序的按钮。我已经尝试过
#with master = Tk()
master.quit()
方法。它对我的程序完全没有任何作用-除了停止任何工作外,尽管我没有收到Tracebacks。
我尝试过的另一种方法是:
#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)
以上方法均无效。
非常感谢(为了将来)
您想将函数对象传递到命令关键字中,因此请不要使用括号。另外,您应该对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)
这应该可以解决您的问题。
问题:
()
的同时将函数(exit
或destroy
)作为Button
传递给command
,这导致它在该位置执行定义。解决方案:
()
或exit
)作为destroy
传递给Button
的同时删除括号command
。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
或任何您想要的东西。您唯一的更改是在属于tk.
的每个对象之前添加tkinter
。然后您的代码如下。
最佳实践:
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()
尝试这个:
from tkinter import *
root = Tk()
Button(root, text="Quit", command=root.destroy).pack()
root.mainloop()