只需对代码进行最少的编辑(不确定他们是否在您的课程中教授过课程),即可更改:
def close_window(root):
root.destroy()
to
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
从未被赋值。就像输入print(x)
当你还没有定义时x
, yet.
看着你的代码,我想你想打电话destroy
on window
,所以我改变了root
to window
.