如何通过按下按钮关闭 Tkinter 窗口? [英] How to close a Tkinter window by pressing a Button?

查看:49
本文介绍了如何通过按下按钮关闭 Tkinter 窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写一个带有标记为 Good-bye" 的按钮的 GUI 应用程序.当...的时候按钮被点击,窗口关闭.

Write a GUI application with a button labeled "Good-bye". When the Button is clicked, the window closes.

到目前为止,这是我的代码,但它不起作用.谁能帮我解决我的代码?

This is my code so far, but it is not working. Can anyone help me out with my code?

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

推荐答案

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

With minimal editing to your code (Not sure if they've taught classes or not in your course), change:

def close_window(root): 
    root.destroy()

def close_window(): 
    window.destroy()

它应该可以工作.

说明:

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

Your version of close_window is defined to expect a single argument, namely root. Subsequently, any calls to your version of close_window need to have that argument, or Python will give you a run-time error.

当您创建Button 时,您告诉按钮在单击时运行close_window.但是,Button 小部件的源代码类似于:

When you created a Button, you told the button to run close_window when it is clicked. However, the source code for Button widget is something like:

# 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 类中执行,我们就剩下:

As my code states, the Button class will call your function with no arguments. However your function is expecting an argument. Thus you had an error. So, if we take out that argument, so that the function call will execute inside the Button class, we're left with:

def close_window(): 
    root.destroy()

但这也不对,因为 root 从未被赋值.这就像在您尚未定义 x 时输入 print(x) 一样.

That's not right, though, either, because root is never assigned a value. It would be like typing in print(x) when you haven't defined x, yet.

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

Looking at your code, I figured you wanted to call destroy on window, so I changed root to window.

这篇关于如何通过按下按钮关闭 Tkinter 窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆