2014-03-13 22 views
2

下面是代碼:類型錯誤:打開()取0位置參數,但2被賦予

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 

我知道開放需要兩個參數。 另外,如果我運行的代碼不在函數內,它可以正常運行而不會出錯。

回答

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會自動關閉它。

+0

這正是我發現和糾正的問題。我發現並重新命名了違規函數,並且它正在正常工作我放在那裏的文本只是用於測試,並不代表實際使用。從那以後,我就寫了真正的代碼,將文本小部件的內容寫入文件。這是工作得很好,就像打開文件並將文本插入文本小部件一樣。我正在做的是創建一個Python IDE,我可以在其中創建一個tkinter GUI而無需編寫任何代碼。 – user3416824

相關問題