PyQt4 TableWidget出现NoneType属性错误

时间:2019-02-24 15:17:00

标签: python python-3.x pyqt pyqt4

我遇到以下错误:

AttributeError: 'NoneType' object has no attribute 'text'

专门从此行:

Item1=self.ProductsTable.item(i,0).text() 

运行此代码时:

from PyQt4.QtGui import * 
from PyQt4.QtCore import * 
import sys,csv,os
import random
import csv_library as csvlib

from PyQt4 import QtCore, QtGui, uic
EditMenu = uic.loadUiType("editmenu.ui")[0]
test=csvlib.csv2list("Food.csv")
NewMenu=[]
class WindowClass6(QtGui.QMainWindow, EditMenu): 
  def __init__(self, parent=None):
    QtGui.QMainWindow.__init__(self, parent)
    self.setupUi(self)
    self.setWindowTitle("Menu")
    self.Save.clicked.connect(self.Save2Menu)
    self.Back.clicked.connect(self.Back2Login)
    ###
    global ProductsTable
    self.ProductsTable.setColumnCount(3)
    self.ProductsTable.setRowCount(11)
    #self.ProductsTable.setHorizontalHeaderLabels(["Food Item", "Price", "Reward Points"])

    for i in range (0,len(test)):
        self.ProductsTable.setItem(i,0, QTableWidgetItem(str(test[i][0])))
        self.ProductsTable.setItem(i,1, QTableWidgetItem(str(test[i][1])))
        self.ProductsTable.setItem(i,2, QTableWidgetItem(str(test[i][2])))

  def Save2Menu(self):
    NewMenu = []
    # do not use global variable, you would get previous items after second call of `Save2Menu` 
    for i in range (0,len(test)):
        Item1=self.ProductsTable.item(i,0).text()  
        # 1) text() will return string representation of item content 
        # 2) pass only 2 parameters as I commented
        print(Item1)
        Item2=self.ProductsTable.item(i,1).text()
        print(Item2)
        Item3=self.ProductsTable.item(i,2).text()
        print(Item3)
        temp=[]
        temp.append(Item1)
        temp.append(Item2)
        temp.append(Item3)
        NewMenu.append(temp)    
    csvlib.list2csv(NewMenu,"Food2.csv")

我研究了NoneType错误,显然,这可能是给我这个问题的,因为表中的单元格中没有值,但是当它生成表时,它看起来像这样: Table

所有值都从先前的for循环中加载,因此我不知道此错误来自何处,其他线程的帮助不多,因此,如果重复或其他任何操作,都感到抱歉。

“ csv_library”:

import csv  
import os
def csv2list(file_name):
list_name=[]
with open(file_name) as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        list_name.append(row)
return list_name

def list2csv(list_name,file_name):
#write back to the csv
with open(file_name, 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerows(list_name)
#it's a procedure, nothing returned

def launch_file(file_name):   
    os.startfile(file_name)

CSV文件内容:(12行3列)

Cheeseburger,14,14
CokeCherry ,1,1
Chickenburger,13,13
ChickenNuggets,8,8
Coke ,1,1
CokeZero ,1,1
Fries,4.5,4.5
MeatFeastPizza,20,20
OnionRings,6,6
PepperoniPizza,16,16
VeggiPizza,22,22
TheVeggieBurger,15,15

0 个答案:

没有答案
相关问题