Reputation: 182
I have written this piece of code to implement data to Listbox when I open a file, though there is an AttributeError, I have failed to understand to fix this error.
from Tkinter import *
import tkFileDialog
import csv
from imdb import IMDb
class STproject:
def __init__(self,app): #1
self.mlb=LabelFrame(app, text='Movie Recommendation Engine')
self.mlb.grid()
self.lframe3=LabelFrame(self.mlb,text="Movies/Users",background='purple')
self.lframe3.grid(row=0,column=1)
self.framebutton=Frame(self.mlb,background='pink',height=50,width=50)
self.framebutton.grid(row=0,column=0)
self.buttonsnlabels()
def buttonsnlabels(self):
self.ratingbutton=Button(self.framebutton,text='Upload Rating',command=lambda :self.file2())
self.ratingbutton.grid()
self.lb1 = Listbox(self.lframe3)
self.lb1.grid()
self.lb1.insert(self.emp2) //self.emp2 its locally ?
def file2(self):
umovies=tkFileDialog.askopenfilename()
f=open(umovies)
self.emp2=[]
self.csv_file2 = csv.reader(f)
for line2 in self.csv_file2:
self.emp2.append(line2[2])
root=Tk()
root.title()
application=STproject(root)
root.mainloop()
and here you have the full error:
Traceback (most recent call last):
File "C:/Users/Umer Selmani/Desktop/voluntarily/Voluntiraly.py", line 846, in <module>
application=STproject(root)
File "C:/Users/Umer Selmani/Desktop/voluntarily/Voluntiraly.py", line 814, in __init__
self.a=self.emp2[1]
AttributeError: STproject instance has no attribute 'emp2'
Upvotes: 0
Views: 124
Reputation: 143097
You have this error because your .insert(self.emp2)
is executed after button is created, not after user clicked button. And at this moment you don't have self.emp2
yet - you create it later in file2()
.
You have to use .insert(self.emp2)
in file2()
EDIT: You have to use insert inside for
loop and add every item separatelly
self.lb1.insert('end', line2[2])
so you could skip self.emp2
if you don't need it later
Or you have to use *
to put items from list in separated lines
self.lb1.insert('end', *self.emp2)
Code
def buttonsnlabels(self):
self.ratingbutton = Button(self.framebutton, text='Upload Rating', command=self.file2)
self.ratingbutton.grid()
self.lb1 = Listbox(self.lframe3)
self.lb1.grid()
def file2(self):
#self.emp2 = []
umovies = tkFileDialog.askopenfilename()
f = open(umovies)
self.csv_file2 = csv.reader(f)
for line2 in self.csv_file2:
#self.emp2.append(line2[2])
self.lb1.insert('end', line2[2])
#self.lb1.insert('end', *self.emp2)
Upvotes: 1