如何按下按钮关闭Tkinter窗口?

2024-03-28 09:46:34 发布

您现在位置:Python中文网/ 问答频道 /正文

用标签为"Good-bye"的按钮编写一个GUI应用程序。当 Button单击,窗口关闭。

到目前为止,这是我的代码,但它不起作用。有人能帮我写密码吗?

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()

Tags: 代码应用程序密码closeguibuttonroot标签
3条回答

可以将函数对象window.destroy直接关联到buttoncommand属性:

button = Button (frame, text="Good-bye.", command=window.destroy)

这样您就不需要函数close_window来为您关闭窗口。

只需对代码进行最少的编辑(不确定他们是否教过课程),就可以更改:

def close_window(root): 
    root.destroy()

def close_window(): 
    window.destroy()

它应该能起作用。


说明:

您的close_window版本被定义为只需要一个参数,即root。随后,任何对close_window版本的调用都需要有该参数,否则Python将给您一个运行时错误

当您创建一个Button时,您告诉按钮在单击时运行close_window。但是,Button小部件的源代码如下:

# 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)

看看你的代码,我想你想在window上调用destroy,所以我把root改为window

您可以创建一个扩展TkinterButton类的类,该类将通过将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()

这是输出:

enter image description here


以及之前代码不起作用的原因:

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()

相关问题 更多 >