@abushama. One proble was you were setting the date to be the ui.DatePicker, not the attr date. You can see I changed it in your function (I missed that originally, I didn't run the code because you didn't post it all, so it was easy for me to miss that). Look, I just got it working in the way i thought you had tried to get it working.
Your calndr function looks likes it would make more sense for you to put it into the class as a method.
I am often torn about how to help. If I make too many changes it can be frustrating to the person and confuse them more. @JonB point about going over your code is very valid. The way you where calling your function again inside trying to write to the csv file was way off. So I would suggest to take what i have done and try to move your calndr function into the class. Then really look closely about what's happening when you are writing out your csv file.
You are not that far away. Just take your time and really look through it. Still here if you need more help.
EDIT please see the notes I added to the bottom of the post.
import ui
import csv
def calndr(sender):
date = sender.superview['calender'].date
# assuming that is the name of your DatePicker object
# this returns a datetime.datetime object, see module datetime
year = date.year
month = date.month
with open('newfile.csv', 'a') as csvfile:
fieldnames = ['Year', 'Month']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writerow({'Year': year, 'Month': month})
class MyClass(ui.View):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.make_view()
def make_view(self):
dtp = ui.DatePicker(name='calender')
btn = ui.Button(width=80,
height=32,
border_width=.5,
bg_color='white',
corner_radius=.5,
action=calndr)
btn.title='Save'
# just position the button
btn.center = self.center
btn.y = self.height - (btn.height * 2)
# add the date picker & btn to the view
self.add_subview(dtp)
self.add_subview(btn)
if __name__ == '__main__':
f = (0, 0, 300, 400)
v = MyClass(frame = f)
v.present(style='sheet', animated=False)
Btw, the csv writer has other methods, for example to write out the headers to you file. Of course you would only want to write the headers once. Oh, I should have mentioned, you should not really move your calndr function into the class the way it is. It really should be a method that just is passed you year and month and writes out the csv file. You really don't want the other objects around. If you make the method just to handle the csv file, you could for example reuse that code in other objects.