gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:31:08 32 4
gpt4 key购买 nike

编写一个带有标签为“再见” 的按钮的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()

最佳答案

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

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.

关于python - 如何通过按下按钮关闭 Tkinter 窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9987624/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com