如何通过按下按钮来关闭Tkinter窗口?
使用标有"Good-bye"
的按钮编写GUI应用程序。当点击该窗口时,该窗口关闭。如何通过按下按钮来关闭Tkinter窗口?
这是我的代码到目前为止,但它不工作。任何人都可以帮我解决我的代码吗?
from Tkinter import *
window = Tk()
def close_window (root):
root.destroy()
frame = Frame(window)
frame.pack()
button = Button (frame, text = "Good-bye.", command = close_window)
button.pack()
window.mainloop()
你可以创建一个类,扩展了Tkinter的Button
类,将被专门由destroy
方法关联到其command
属性关闭窗口:
from tkinter import *
class quitButton(Button):
def __init__(self, parent):
Button.__init__(self, parent)
self['text'] = 'Good Bye'
# Command to close the window (the destory method)
self['command'] = parent.destroy
self.pack(side=BOTTOM)
root = Tk()
quitButton(root)
mainloop()
这是输出:
为什么之前你的代码没有工作的原因:
def close_window():
# root.destroy()
window.destroy()
我中有你可能有根从别的地方有轻微的感觉,因为你没有window = tk()
。
当您在Tkinter中调用window
上的destroy时,意味着销毁整个应用程序,因为您的window
(根窗口)是应用程序的主窗口。恕我直言,我认为你应该改变你的window
为root
。
from tkinter import *
def close_window():
root.destroy() # destroying the main window
root = Tk()
frame = Frame(root)
frame.pack()
button = Button(frame)
button['text'] ="Good-bye."
button['command'] = close_window
button.pack()
mainloop()
以最小的编辑到您的代码(不知道他们有没有教课或不在您的课程),更改:
def close_window(root):
root.destroy()
到
def close_window():
window.destroy()
,它应该工作。
说明:
你的close_window
版本被定义为期望一个参数,即root
。随后,任何对您的close_window
版本的调用都需要这个参数,否则Python会给您一个运行时错误。
当您创建Button
时,您告知按钮单击时运行close_window
。然而,对于按钮插件的源代码是一样的东西:
# class constructor
def __init__(self, some_args, command, more_args):
#...
self.command = command
#...
# this method is called when the user clicks the button
def clicked(self):
#...
self.command() # Button calls your function with no arguments.
#...
至于我的代码州,Button
类将调用你的函数不带参数。然而你的功能正在期待一个论点。因此你有一个错误。所以,如果我们采取了这样的说法,这样的函数调用将Button类内部执行,我们就只剩下:
def close_window():
root.destroy()
这是不对的,但是,无论是,因为root
从未赋值。这就好像你还没有定义x
时输入print(x)
。
看你的代码,我想你想叫destroy
上window
,所以我改变root
到window
。
您可以使用lambda
向window
对象作为参数的引用传递给close_window
功能:
button = Button (frame, text="Good-bye.", command = lambda: close_window(window))
这工作,因为command
属性期待一个调用,或可调用状物体。 A lambda
是可调用的,但在本例中它基本上是使用设置参数调用给定函数的结果。
实际上,您正在调用没有args的函数的lambda包装器,而不是函数本身。
您可以将函数对象window.destroy
直接关联到你的button
的command
属性:
button = Button (frame, text="Good-bye.", command=window.destroy)
这样你就不需要功能close_window
关闭窗口为您服务。
from tkinter import *
def close_window():
import sys
sys.exit()
root = Tk()
frame = Frame (root)
frame.pack()
button = Button (frame, text="Good-bye", command=close_window)
button.pack()
mainloop()
嘿马特。感谢您提出明确的问题,并附上简洁明了的代码示例。当你的代码“不能正常工作”时,你能否确保在将来包含追溯(崩溃)?这也将帮助人们几乎立即弄清楚代码的哪部分被破坏了。很显然,在这种情况下,你的代码样本非常小,很容易识别,但它可能确实有助于你在更困难的情况下获得答案。 – jdi 2012-04-03 06:47:11
对于没有立即看到问题的人,错误是'TypeError:close_window()缺少1个需要的位置参数:'root'。这意味着没有参数传递给回调'close_window',因为从来没有'command ='函数。绑定事件回调确实得到一个参数 - 事件对象。 – 2015-03-17 00:23:13