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

Mat*_*awk 24 python tkinter

使用标记的按钮编写GUI应用程序"Good-bye".当 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()
Run Code Online (Sandbox Code Playgroud)

Wor*_*red 30

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

def close_window(root): 
    root.destroy()
Run Code Online (Sandbox Code Playgroud)

def close_window(): 
    window.destroy()
Run Code Online (Sandbox Code Playgroud)

它应该工作.


说明:

您的版本close_window定义为期望单个参数,即root.随后,对您的版本的任何调用close_window需要具有该参数,或Python将给您一个运行时错误.

创建a时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.
    #...
Run Code Online (Sandbox Code Playgroud)

正如我的代码所述,Button该类将在没有参数的情况下调用您的函数.但是你的功能是期待一个论点.因此你有一个错误.所以,如果我们取出那个参数,那么函数调用将在Button类中执行,我们留下:

def close_window(): 
    root.destroy()
Run Code Online (Sandbox Code Playgroud)

但是,这也不对,因为root永远不会分配价值.print(x)当你还没有定义时x,就像打字一样.

看你的代码,我想你想叫destroywindow,让我改变了rootwindow.


Geo*_*rge 10

您可以创建一个扩展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()
Run Code Online (Sandbox Code Playgroud)

这是输出:

在此输入图像描述


以及您的代码之前没有工作的原因:

def close_window (): 
    # root.destroy()
    window.destroy()
Run Code Online (Sandbox Code Playgroud)

我有一种轻微的感觉,你可能从其他地方得到了根,因为你做到了window = tk().

当您window在Tkinter中调用destroy时意味着销毁整个应用程序,因为您的window(根窗口)是应用程序的主窗口.恕我直言,我认为你应该改变你windowroot.

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()
Run Code Online (Sandbox Code Playgroud)


小智 7

您可以直接将函数对象window.destroycommand您的属性关联button:

button = Button (frame, text="Good-bye.", command=window.destroy)
Run Code Online (Sandbox Code Playgroud)

这样您就不需要该功能close_window来关闭窗口了.


小智 5

from tkinter import *

window = tk()
window.geometry("300x300")

def close_window (): 

    window.destroy()

button = Button ( text = "Good-bye", command = close_window)
button.pack()

window.mainloop()
Run Code Online (Sandbox Code Playgroud)