Python Tkinter关闭窗口

问题描述 投票:0回答:4

在创建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)

以上方法均无效。

非常感谢(为了将来)

python user-interface tkinter grid exit
4个回答
0
投票

您想将函数对象传递到命令关键字中,因此请不要使用括号。另外,您应该对TKinter使用destroy函数。

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

0
投票

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

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)

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


0
投票

问题:

  • 唯一的问题是,您在使用括号()的同时将函数(exitdestroy)作为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()

-1
投票

尝试这个:

from tkinter import *

root = Tk()
Button(root, text="Quit", command=root.destroy).pack()
root.mainloop()
© www.soinside.com 2019 - 2024. All rights reserved.