2017-08-08 52 views
0

當我嘗試運行此代碼時,我收到了以前從未收到的錯誤。子索引超出範圍,python元素樹

File "BasicEmail.py", line 96, in init_ui root[0][1].text IndexError: child index out of range Abort trap: 6

我的代碼很簡單,

class EmailBlast(QtWidgets.QWidget): 
    def __init__(self): 
     super().__init__() 
     self.init_ui() 

    def init_ui(self): 
     user_file = 'user_info.xml' 
     tree = ET.parse(user_file) 
     root = tree.getroot() 
     root[0][1].text 
     self.emailLabel = QtWidgets.QLabel("Email:") 
     self.emailListLabel = QtWidgets.QLabel("") 
     self.sendButton = QtWidgets.QPushButton("Save") 
     self.settingsButton = QtWidgets.QPushButton("Settings") 

     h_box = QtWidgets.QHBoxLayout() 
     h_box.addStretch() 

     v_box = QtWidgets.QVBoxLayout() 
     v_box.addWidget(self.emailLabel) 
     v_box.addWidget(self.emailListLabel) 
     v_box.addWidget(self.sendButton) 
     v_box.addWidget(self.settingsButton)   
     v_box.addLayout(h_box) 

     self.setLayout(v_box) 
     self.setWindowTitle("Email Blast") 

     self.settingsButton.clicked.connect(lambda: self.settings(self.settingsButton, "Saved"))   
     self.show() 

    def settings(self, settingsButton, string): 
     self.ui = ConfigWindow() 
     self.hide()   
     print("Settings") 

我能夠獲得標記和屬性,沒有值。 XML中的數據很好,應該有一個數組或列表,供我從中獲取。

包括完整的XML文件:

<data> 
<email>[email protected]</email> 
<password>testpass</password> 
<smtp>gmail</smtp> 
<port>587</port> 
</data>` 
+0

檢查'tree.getroot()的結果',用'print(len(tree.getroot()))'和'print(len(tree.getroot()[0]))',很難說沒有更多的代碼有什麼錯誤 – PRMoureu

+0

你可以提供.xml – eyllanesc

+0

@PRMoureu 我還會提供xml – EwokHugz

回答

1

你的數據的XML模式直接給出了根裏面的孩子, 所以不需要訪問嵌套子:

root = tree.getroot() 
root[0].text # returns the email 
root[1].text # returns the password 
root[2].text # returns the smtp 
root[3].text # returns the port 

您也可以使用名稱查詢以允許在您的模式中進行一些更改:

root.find('email').text