以下是代码:
def save():
f = open('table.html', 'w')
f.write("<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>\n")
f.write("<html xmlns='http://www.w3.org/1999/xhtml'>\n")
f.write("<head profile='http://gmpg.org/xfn/11'>\n")
f.write('<title>Table</title>')
f.write("<style type='text/css'>")
f.write('body {margin-left:0;margin-right:0;font:normal normal 800 18px Arial;}')
f.write('a{ text-decoration: }')
f.write(':link { color: rgb(0, 0, 255) }')
f.write(':visited {color :rgb(100, 0,100) }')
f.write(':hover { }')
f.write(':active { }')
f.write('table{position: relative; empty-cells: show;border: 1px solid black; border-collapse: collapse}')
f.write('td{position: relative; border: 1px solid black; text-align: left; padding: 0px 5px 0px 1px}')
f.write('.tr1{background: #EEFFF9}')
f.write('.tr2{background: #FFFEEE}')
f.write('</style>')
f.write('</head>')
f.write('<body>')
f.write('<center>2012 La Jolla Half Marathon</center><br />')
f.write('<table>')
f.close()
我得到了这个例外:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python33\lib\tkinter\__init__.py", line 1475, in __call__
return self.func(*args)
File "C:\Python33\GUICreator1.py", line 11, in save
f = open('table.html', 'w')
TypeError: open() takes 0 positional arguments but 2 were given
我知道open需要2个参数。 此外,如果我在函数内运行相同的代码,它运行正常,没有错误。
答案 0 :(得分:4)
在模块的其他位置,您有一个名为open()
(已定义或已导入)的函数可以屏蔽内置函数。重命名。
对于你的save()
函数,你应该使用多行字符串,使用三重引号来保存自己很多f.write()
次调用:
def save():
with open('table.html', 'w') as f:
f.write("""\
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>\n
<html xmlns='http://www.w3.org/1999/xhtml'>\n
<head profile='http://gmpg.org/xfn/11'>\n
<title>Table</title>
<style type='text/css'>
body {margin-left:0;margin-right:0;font:normal normal 800 18px Arial;}
a{ text-decoration: }
:link { color: rgb(0, 0, 255) }
:visited {color :rgb(100, 0,100) }
:hover { }
:active { }
table{position: relative; empty-cells: show;border: 1px solid black; border-collapse: collapse}
td{position: relative; border: 1px solid black; text-align: left; padding: 0px 5px 0px 1px}
.tr1{background: #EEFFF9}
.tr2{background: #FFFEEE}
</style>
</head>
<body>
<center>2012 La Jolla Half Marathon</center><br />
<table>""")
这也使用开放文件对象作为上下文管理器,这意味着Python将自动关闭它。